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

Patch by Sergey Prigogin for bug 148582 - Support smart indenting in C editor (part 2)

This commit is contained in:
Anton Leherbauer 2006-10-02 13:06:08 +00:00
parent ae1ab1b625
commit 0482b39544
65 changed files with 11320 additions and 2446 deletions

View file

@ -14,6 +14,7 @@ package org.eclipse.cdt.core;
import java.util.Map;
import org.eclipse.cdt.core.formatter.CodeFormatter;
import org.eclipse.cdt.internal.formatter.CCodeFormatter;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
@ -67,5 +68,8 @@ public class ToolFactory {
return null;
}
public static CodeFormatter createDefaultCodeFormatter(Map options){
if (options == null) options = CCorePlugin.getOptions();
return new CCodeFormatter(options);
}
}

View file

@ -21,6 +21,8 @@ import org.eclipse.text.edits.TextEdit;
*/
public abstract class CodeFormatter {
public static final String EMPTY_STRING = ""; //$NON-NLS-1$
/**
* Unknown kind
*/
@ -46,6 +48,15 @@ public abstract class CodeFormatter {
*/
public static final int K_COMPILATION_UNIT = 0x08;
/**
* Kind used to format a single-line comment
*/
public static final int K_SINGLE_LINE_COMMENT = 0x10;
/**
* Kind used to format a multi-line comment
*/
public static final int K_MULTI_LINE_COMMENT = 0x20;
/**
* Format <code>source</code>,
* and returns a text edit that correspond to the difference between the given string and the formatted string.
@ -75,4 +86,19 @@ public abstract class CodeFormatter {
* @param options - general formatter options
*/
public abstract void setOptions(Map options);
/**
* Answers the string that corresponds to the indentation to the given indentation level or an empty string
* if the indentation cannot be computed.
* <p>This method needs to be overriden in a subclass.</p>
*
* <p>The default implementation returns an empty string.</p>
*
* @param indentationLevel the given indentation level
* @return the string corresponding to the right indentation level
* @exception IllegalArgumentException if the given indentation level is lower than zero
*/
public String createIndentationString(int indentationLevel) {
return EMPTY_STRING;
}
}

View file

@ -19,7 +19,7 @@ import org.eclipse.cdt.internal.formatter.align.Alignment;
/**
*/
public class CodeFormatterConstants {
public class DefaultCodeFormatterConstants {
/**
* <pre>
@ -494,75 +494,63 @@ public class CodeFormatterConstants {
*/
public static final String FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION = CCorePlugin.PLUGIN_ID + ".formatter.brace_position_for_type_declaration"; //$NON-NLS-1$
// /**
// * <pre>
// * FORMATTER / Option to control whether blank lines are cleared inside comments
// * - option id: "org.eclipse.cdt.core.formatter.comment.clear_blank_lines"
// * - possible values: { TRUE, FALSE }
// * - default: FALSE
// * </pre>
// * @see #TRUE
// * @see #FALSE
// */
// public final static String FORMATTER_COMMENT_CLEAR_BLANK_LINES = CCorePlugin.PLUGIN_ID + ".formatter.comment.clear_blank_lines"; //$NON-NLS-1$
/**
* <pre>
* FORMATTER / Option to control whether blank lines are cleared inside comments
* - option id: "org.eclipse.cdt.core.formatter.comment.clear_blank_lines"
* - possible values: { TRUE, FALSE }
* - default: FALSE
* </pre>
* @see #TRUE
* @see #FALSE
*/
public final static String FORMATTER_COMMENT_CLEAR_BLANK_LINES = CCorePlugin.PLUGIN_ID + ".formatter.comment.clear_blank_lines"; //$NON-NLS-1$
// /**
// * <pre>
// * FORMATTER / Option to control whether comments are formatted
// * - option id: "org.eclipse.cdt.core.formatter.comment.format_comments"
// * - possible values: { TRUE, FALSE }
// * - default: TRUE
// * </pre>
// * @see #TRUE
// * @see #FALSE
// */
// public final static String FORMATTER_COMMENT_FORMAT = CCorePlugin.PLUGIN_ID + ".formatter.comment.format_comments"; //$NON-NLS-1$
/**
* <pre>
* FORMATTER / Option to control whether comments are formatted
* - option id: "org.eclipse.cdt.core.formatter.comment.format_comments"
* - possible values: { TRUE, FALSE }
* - default: TRUE
* </pre>
* @see #TRUE
* @see #FALSE
*/
public final static String FORMATTER_COMMENT_FORMAT = CCorePlugin.PLUGIN_ID + ".formatter.comment.format_comments"; //$NON-NLS-1$
// /**
// * <pre>
// * FORMATTER / Option to control whether the header comment of a C/C++ source file is formatted
// * - option id: "org.eclipse.cdt.core.formatter.comment.format_header"
// * - possible values: { TRUE, FALSE }
// * - default: FALSE
// * </pre>
// * @see #TRUE
// * @see #FALSE
// */
// public final static String FORMATTER_COMMENT_FORMAT_HEADER = CCorePlugin.PLUGIN_ID + ".formatter.comment.format_header"; //$NON-NLS-1$
/**
* <pre>
* FORMATTER / Option to control whether the header comment of a C/C++ source file is formatted
* - option id: "org.eclipse.cdt.core.formatter.comment.format_header"
* - possible values: { TRUE, FALSE }
* - default: FALSE
* </pre>
* @see #TRUE
* @see #FALSE
*/
public final static String FORMATTER_COMMENT_FORMAT_HEADER = CCorePlugin.PLUGIN_ID + ".formatter.comment.format_header"; //$NON-NLS-1$
// /**
// * <pre>
// * FORMATTER / Option to control whether HTML tags are formatted.
// * - option id: "org.eclipse.cdt.core.formatter.comment.format_html"
// * - possible values: { TRUE, FALSE }
// * - default: TRUE
// * </pre>
// * @see #TRUE
// * @see #FALSE
// */
// public final static String FORMATTER_COMMENT_FORMAT_HTML = CCorePlugin.PLUGIN_ID + ".formatter.comment.format_html"; //$NON-NLS-1$
/**
* <pre>
* FORMATTER / Option to control whether code snippets are formatted in comments
* - option id: "org.eclipse.cdt.core.formatter.comment.format_source_code"
* - possible values: { TRUE, FALSE }
* - default: TRUE
* </pre>
* @see #TRUE
* @see #FALSE
*/
public final static String FORMATTER_COMMENT_FORMAT_SOURCE = CCorePlugin.PLUGIN_ID + ".formatter.comment.format_source_code"; //$NON-NLS-1$
// /**
// * <pre>
// * FORMATTER / Option to control whether code snippets are formatted in comments
// * - option id: "org.eclipse.cdt.core.formatter.comment.format_source_code"
// * - possible values: { TRUE, FALSE }
// * - default: TRUE
// * </pre>
// * @see #TRUE
// * @see #FALSE
// */
// public final static String FORMATTER_COMMENT_FORMAT_SOURCE = CCorePlugin.PLUGIN_ID + ".formatter.comment.format_source_code"; //$NON-NLS-1$
// /**
// * <pre>
// * FORMATTER / Option to specify the line length for comments.
// * - option id: "org.eclipse.cdt.core.formatter.comment.line_length"
// * - possible values: "&lt;n&gt;", where n is zero or a positive integer
// * - default: "80"
// * </pre>
// */
// public final static String FORMATTER_COMMENT_LINE_LENGTH = CCorePlugin.PLUGIN_ID + ".formatter.comment.line_length"; //$NON-NLS-1$
/**
* <pre>
* FORMATTER / Option to specify the line length for comments.
* - option id: "org.eclipse.cdt.core.formatter.comment.line_length"
* - possible values: "&lt;n&gt;", where n is zero or a positive integer
* - default: "80"
* </pre>
*/
public final static String FORMATTER_COMMENT_LINE_LENGTH = CCorePlugin.PLUGIN_ID + ".formatter.comment.line_length"; //$NON-NLS-1$
// /**
// * <pre>
@ -630,14 +618,25 @@ public class CodeFormatterConstants {
/**
* <pre>
* FORMATTER / Option to indent body declarations compare to its enclosing type header
* - option id: "org.eclipse.cdt.core.formatter.indent_body_declarations_compare_to_type_header"
* - option id: "org.eclipse.cdt.core.formatter.indent_access_specifier_compare_to_type_header"
* - possible values: { TRUE, FALSE }
* - default: FALSE
* </pre>
* @see #TRUE
* @see #FALSE
*/
public static final String FORMATTER_INDENT_ACCESS_SPECIFIER_COMPARE_TO_TYPE_HEADER = CCorePlugin.PLUGIN_ID + ".formatter.indent_access_specifier_compare_to_type_header"; //$NON-NLS-1$
/**
* <pre>
* FORMATTER / Option to indent body declarations compare to its enclosing type header
* - option id: "org.eclipse.cdt.core.formatter.indent_body_declarations_compare_to_access_specifier"
* - possible values: { TRUE, FALSE }
* - default: TRUE
* </pre>
* @see #TRUE
* @see #FALSE
*/
public static final String FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_TYPE_HEADER = CCorePlugin.PLUGIN_ID + ".formatter.indent_body_declarations_compare_to_type_header"; //$NON-NLS-1$
public static final String FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ACCESS_SPECIFIER = CCorePlugin.PLUGIN_ID + ".formatter.indent_body_declarations_compare_to_access_specifier"; //$NON-NLS-1$
/**
* <pre>
* FORMATTER / Option to indent breaks compare to cases
@ -1119,7 +1118,7 @@ public class CodeFormatterConstants {
// /**
// * <pre>
// * FORMATTER / Option to insert a space after the comma in the arguments of an explicit constructor call
// * - option id: "org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments"
// * - option id: "org.eclipse.cdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments"
// * - possible values: { INSERT, DO_NOT_INSERT }
// * - default: INSERT
// * </pre>

View file

@ -17,7 +17,7 @@ import java.util.Map;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.CCorePreferenceConstants;
import org.eclipse.cdt.core.formatter.CodeFormatterConstants;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.cdt.internal.core.model.CModelManager;
//import org.eclipse.core.runtime.Preferences;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
@ -35,7 +35,7 @@ public class CCorePreferenceInitializer extends AbstractPreferenceInitializer {
HashSet optionNames = CModelManager.OptionNames;
// Formatter settings
Map defaultOptionsMap = CodeFormatterConstants.getEclipseDefaultSettings(); // code formatter defaults
Map defaultOptionsMap = DefaultCodeFormatterConstants.getEclipseDefaultSettings(); // code formatter defaults
// Compiler settings
defaultOptionsMap.put(CCorePreferenceConstants.TRANSLATION_TASK_TAGS, CCorePreferenceConstants.DEFAULT_TASK_TAG);

View file

@ -7,24 +7,90 @@
*
* Contributors:
* QNX Software Systems - Initial API and implementation
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.formatter;
import java.util.Map;
public class CCodeFormatter {
//public FormatterOptions options;
import org.eclipse.cdt.core.formatter.CodeFormatter;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.text.edits.TextEdit;
public class CCodeFormatter extends CodeFormatter {
private DefaultCodeFormatterOptions preferences;
public CCodeFormatter() {
this(new DefaultCodeFormatterOptions(DefaultCodeFormatterConstants.getEclipseDefaultSettings()), null);
}
// CCodeFormatter(FormatterOptions options) {
// }
public String formatSourceString(String content) {
return content;
public CCodeFormatter(DefaultCodeFormatterOptions preferences) {
this(preferences, null);
}
public CCodeFormatter(DefaultCodeFormatterOptions defaultCodeFormatterOptions, Map options) {
setOptions(options);
if (defaultCodeFormatterOptions != null) {
preferences.set(defaultCodeFormatterOptions.getMap());
}
}
public CCodeFormatter(Map options) {
this(null, options);
}
public String createIndentationString(final int indentationLevel) {
if (indentationLevel < 0) {
throw new IllegalArgumentException();
}
int tabs = 0;
int spaces = 0;
switch (preferences.tab_char) {
case DefaultCodeFormatterOptions.SPACE :
spaces = indentationLevel * preferences.tab_size;
break;
case DefaultCodeFormatterOptions.TAB :
tabs = indentationLevel;
break;
case DefaultCodeFormatterOptions.MIXED :
int tabSize = preferences.tab_size;
int spaceEquivalents = indentationLevel * preferences.indentation_size;
tabs = spaceEquivalents / tabSize;
spaces = spaceEquivalents % tabSize;
break;
default:
return EMPTY_STRING;
}
if (tabs == 0 && spaces == 0) {
return EMPTY_STRING;
}
StringBuffer buffer = new StringBuffer(tabs + spaces);
for (int i = 0; i < tabs; i++) {
buffer.append('\t');
}
for(int i = 0; i < spaces; i++) {
buffer.append(' ');
}
return buffer.toString();
}
public void setOptions(Map options) {
if (options != null) {
preferences = new DefaultCodeFormatterOptions(options);
} else {
preferences = new DefaultCodeFormatterOptions(DefaultCodeFormatterConstants.getEclipseDefaultSettings());
}
}
public TextEdit format(int kind, String source, int offset, int length, int indentationLevel, String lineSeparator) {
// TODO Not implemented yet
return null;
}
}

View file

@ -14,7 +14,7 @@ package org.eclipse.cdt.internal.formatter;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.cdt.core.formatter.CodeFormatterConstants;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.internal.formatter.align.Alignment;
@ -95,7 +95,8 @@ public class DefaultCodeFormatterOptions {
public boolean indent_statements_compare_to_body;
public boolean indent_body_declarations_compare_to_enum_constant_header;
public boolean indent_body_declarations_compare_to_enum_declaration_header;
public boolean indent_body_declarations_compare_to_type_header;
public boolean indent_body_declarations_compare_to_access_specifier;
public boolean indent_access_specifier_compare_to_type_header;
public boolean indent_breaks_compare_to_cases;
public boolean indent_empty_lines;
public boolean indent_switchstatements_compare_to_cases;
@ -288,44 +289,44 @@ public class DefaultCodeFormatterOptions {
public Map getMap() {
Map options = new HashMap();
options.put(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_ALLOCATION_EXPRESSION, getAlignment(this.alignment_for_arguments_in_allocation_expression));
options.put(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_ENUM_CONSTANT, getAlignment(this.alignment_for_arguments_in_enum_constant));
options.put(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_EXPLICIT_CONSTRUCTOR_CALL, getAlignment(this.alignment_for_arguments_in_explicit_constructor_call));
options.put(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION, getAlignment(this.alignment_for_arguments_in_method_invocation));
options.put(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_QUALIFIED_ALLOCATION_EXPRESSION, getAlignment(this.alignment_for_arguments_in_qualified_allocation_expression));
options.put(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ASSIGNMENT, getAlignment(this.alignment_for_assignment));
options.put(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_BINARY_EXPRESSION, getAlignment(this.alignment_for_binary_expression));
options.put(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_COMPACT_IF, getAlignment(this.alignment_for_compact_if));
options.put(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_CONDITIONAL_EXPRESSION, getAlignment(this.alignment_for_conditional_expression));
options.put(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ENUM_CONSTANTS, getAlignment(this.alignment_for_enum_constants));
options.put(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_ARRAY_INITIALIZER, getAlignment(this.alignment_for_expressions_in_array_initializer));
options.put(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_MULTIPLE_FIELDS, getAlignment(this.alignment_for_multiple_fields));
options.put(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_CONSTRUCTOR_DECLARATION, getAlignment(this.alignment_for_parameters_in_constructor_declaration));
options.put(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION, getAlignment(this.alignment_for_parameters_in_method_declaration));
options.put(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SELECTOR_IN_METHOD_INVOCATION, getAlignment(this.alignment_for_selector_in_method_invocation));
options.put(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SUPERCLASS_IN_TYPE_DECLARATION, getAlignment(this.alignment_for_superclass_in_type_declaration));
options.put(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SUPERINTERFACES_IN_ENUM_DECLARATION, getAlignment(this.alignment_for_superinterfaces_in_enum_declaration));
options.put(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SUPERINTERFACES_IN_TYPE_DECLARATION, getAlignment(this.alignment_for_superinterfaces_in_type_declaration));
options.put(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_THROWS_CLAUSE_IN_CONSTRUCTOR_DECLARATION, getAlignment(this.alignment_for_throws_clause_in_constructor_declaration));
options.put(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_THROWS_CLAUSE_IN_METHOD_DECLARATION, getAlignment(this.alignment_for_throws_clause_in_method_declaration));
options.put(CodeFormatterConstants.FORMATTER_ALIGN_TYPE_MEMBERS_ON_COLUMNS, this.align_type_members_on_columns ? CodeFormatterConstants.TRUE : CodeFormatterConstants.FALSE);
options.put(CodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ARRAY_INITIALIZER, this.brace_position_for_array_initializer);
options.put(CodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_BLOCK, this.brace_position_for_block);
options.put(CodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_BLOCK_IN_CASE, this.brace_position_for_block_in_case);
options.put(CodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_CONSTRUCTOR_DECLARATION, this.brace_position_for_constructor_declaration);
options.put(CodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ENUM_CONSTANT, this.brace_position_for_enum_constant);
options.put(CodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ENUM_DECLARATION, this.brace_position_for_enum_declaration);
options.put(CodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION, this.brace_position_for_method_declaration);
options.put(CodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION, this.brace_position_for_type_declaration);
options.put(CodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_SWITCH, this.brace_position_for_switch);
options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_ALLOCATION_EXPRESSION, getAlignment(this.alignment_for_arguments_in_allocation_expression));
options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_ENUM_CONSTANT, getAlignment(this.alignment_for_arguments_in_enum_constant));
options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_EXPLICIT_CONSTRUCTOR_CALL, getAlignment(this.alignment_for_arguments_in_explicit_constructor_call));
options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION, getAlignment(this.alignment_for_arguments_in_method_invocation));
options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_QUALIFIED_ALLOCATION_EXPRESSION, getAlignment(this.alignment_for_arguments_in_qualified_allocation_expression));
options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ASSIGNMENT, getAlignment(this.alignment_for_assignment));
options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_BINARY_EXPRESSION, getAlignment(this.alignment_for_binary_expression));
options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_COMPACT_IF, getAlignment(this.alignment_for_compact_if));
options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_CONDITIONAL_EXPRESSION, getAlignment(this.alignment_for_conditional_expression));
options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ENUM_CONSTANTS, getAlignment(this.alignment_for_enum_constants));
options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_ARRAY_INITIALIZER, getAlignment(this.alignment_for_expressions_in_array_initializer));
options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_MULTIPLE_FIELDS, getAlignment(this.alignment_for_multiple_fields));
options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_CONSTRUCTOR_DECLARATION, getAlignment(this.alignment_for_parameters_in_constructor_declaration));
options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION, getAlignment(this.alignment_for_parameters_in_method_declaration));
options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SELECTOR_IN_METHOD_INVOCATION, getAlignment(this.alignment_for_selector_in_method_invocation));
options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SUPERCLASS_IN_TYPE_DECLARATION, getAlignment(this.alignment_for_superclass_in_type_declaration));
options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SUPERINTERFACES_IN_ENUM_DECLARATION, getAlignment(this.alignment_for_superinterfaces_in_enum_declaration));
options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SUPERINTERFACES_IN_TYPE_DECLARATION, getAlignment(this.alignment_for_superinterfaces_in_type_declaration));
options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_THROWS_CLAUSE_IN_CONSTRUCTOR_DECLARATION, getAlignment(this.alignment_for_throws_clause_in_constructor_declaration));
options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_THROWS_CLAUSE_IN_METHOD_DECLARATION, getAlignment(this.alignment_for_throws_clause_in_method_declaration));
options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGN_TYPE_MEMBERS_ON_COLUMNS, this.align_type_members_on_columns ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
options.put(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ARRAY_INITIALIZER, this.brace_position_for_array_initializer);
options.put(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_BLOCK, this.brace_position_for_block);
options.put(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_BLOCK_IN_CASE, this.brace_position_for_block_in_case);
options.put(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_CONSTRUCTOR_DECLARATION, this.brace_position_for_constructor_declaration);
options.put(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ENUM_CONSTANT, this.brace_position_for_enum_constant);
options.put(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ENUM_DECLARATION, this.brace_position_for_enum_declaration);
options.put(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION, this.brace_position_for_method_declaration);
options.put(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION, this.brace_position_for_type_declaration);
options.put(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_SWITCH, this.brace_position_for_switch);
// options.put(CodeFormatterConstants.FORMATTER_COMMENT_CLEAR_BLANK_LINES, this.comment_clear_blank_lines ? CodeFormatterConstants.TRUE : CodeFormatterConstants.FALSE);
// options.put(CodeFormatterConstants.FORMATTER_COMMENT_FORMAT, this.comment_format ? CodeFormatterConstants.TRUE : CodeFormatterConstants.FALSE);
// options.put(CodeFormatterConstants.FORMATTER_COMMENT_FORMAT_HEADER, this.comment_format_header ? CodeFormatterConstants.TRUE : CodeFormatterConstants.FALSE);
// options.put(CodeFormatterConstants.FORMATTER_COMMENT_FORMAT_HTML, this.comment_format_html ? CodeFormatterConstants.TRUE : CodeFormatterConstants.FALSE);
// options.put(CodeFormatterConstants.FORMATTER_COMMENT_FORMAT_SOURCE, this.comment_format_source ? CodeFormatterConstants.TRUE : CodeFormatterConstants.FALSE);
// options.put(CodeFormatterConstants.FORMATTER_COMMENT_LINE_LENGTH, Integer.toString(this.comment_line_length));
options.put(CodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION, Integer.toString(this.continuation_indentation));
options.put(CodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION_FOR_ARRAY_INITIALIZER, Integer.toString(this.continuation_indentation_for_array_initializer));
options.put(DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION, Integer.toString(this.continuation_indentation));
options.put(DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION_FOR_ARRAY_INITIALIZER, Integer.toString(this.continuation_indentation_for_array_initializer));
// options.put(CodeFormatterConstants.FORMATTER_BLANK_LINES_AFTER_IMPORTS, Integer.toString(this.blank_lines_after_imports));
// options.put(CodeFormatterConstants.FORMATTER_BLANK_LINES_AFTER_PACKAGE, Integer.toString(this.blank_lines_after_package));
// options.put(CodeFormatterConstants.FORMATTER_BLANK_LINES_BEFORE_FIELD, Integer.toString(this.blank_lines_before_field));
@ -337,16 +338,18 @@ public class DefaultCodeFormatterOptions {
// options.put(CodeFormatterConstants.FORMATTER_BLANK_LINES_BEFORE_PACKAGE, Integer.toString(this.blank_lines_before_package));
// options.put(CodeFormatterConstants.FORMATTER_BLANK_LINES_BETWEEN_TYPE_DECLARATIONS, Integer.toString(this.blank_lines_between_type_declarations));
// options.put(CodeFormatterConstants.FORMATTER_BLANK_LINES_AT_BEGINNING_OF_METHOD_BODY, Integer.toString(this.blank_lines_at_beginning_of_method_body));
options.put(CodeFormatterConstants.FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BLOCK, this.indent_statements_compare_to_block ? CodeFormatterConstants.TRUE : CodeFormatterConstants.FALSE);
options.put(CodeFormatterConstants.FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BODY, this.indent_statements_compare_to_body ? CodeFormatterConstants.TRUE : CodeFormatterConstants.FALSE);
options.put(CodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ENUM_CONSTANT_HEADER, this.indent_body_declarations_compare_to_enum_constant_header ? CodeFormatterConstants.TRUE : CodeFormatterConstants.FALSE);
options.put(CodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ENUM_DECLARATION_HEADER, this.indent_body_declarations_compare_to_enum_declaration_header ? CodeFormatterConstants.TRUE : CodeFormatterConstants.FALSE);
options.put(CodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_TYPE_HEADER, this.indent_body_declarations_compare_to_type_header ? CodeFormatterConstants.TRUE : CodeFormatterConstants.FALSE);
options.put(CodeFormatterConstants.FORMATTER_INDENT_BREAKS_COMPARE_TO_CASES, this.indent_breaks_compare_to_cases ? CodeFormatterConstants.TRUE : CodeFormatterConstants.FALSE);
options.put(CodeFormatterConstants.FORMATTER_INDENT_EMPTY_LINES, this.indent_empty_lines ? CodeFormatterConstants.TRUE : CodeFormatterConstants.FALSE);
options.put(CodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_CASES, this.indent_switchstatements_compare_to_cases ? CodeFormatterConstants.TRUE : CodeFormatterConstants.FALSE);
options.put(CodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_SWITCH, this.indent_switchstatements_compare_to_switch ? CodeFormatterConstants.TRUE : CodeFormatterConstants.FALSE);
options.put(CodeFormatterConstants.FORMATTER_INDENTATION_SIZE, Integer.toString(this.indentation_size));
options.put(DefaultCodeFormatterConstants.FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BLOCK, this.indent_statements_compare_to_block ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
options.put(DefaultCodeFormatterConstants.FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BODY, this.indent_statements_compare_to_body ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
options.put(DefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ENUM_CONSTANT_HEADER, this.indent_body_declarations_compare_to_enum_constant_header ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
options.put(DefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ENUM_DECLARATION_HEADER, this.indent_body_declarations_compare_to_enum_declaration_header ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
options.put(DefaultCodeFormatterConstants.FORMATTER_INDENT_ACCESS_SPECIFIER_COMPARE_TO_TYPE_HEADER, this.indent_body_declarations_compare_to_access_specifier ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
options.put(DefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ACCESS_SPECIFIER, this.indent_body_declarations_compare_to_access_specifier ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
options.put(DefaultCodeFormatterConstants.FORMATTER_INDENT_ACCESS_SPECIFIER_COMPARE_TO_TYPE_HEADER, this.indent_access_specifier_compare_to_type_header ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
options.put(DefaultCodeFormatterConstants.FORMATTER_INDENT_BREAKS_COMPARE_TO_CASES, this.indent_breaks_compare_to_cases ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
options.put(DefaultCodeFormatterConstants.FORMATTER_INDENT_EMPTY_LINES, this.indent_empty_lines ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
options.put(DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_CASES, this.indent_switchstatements_compare_to_cases ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
options.put(DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_SWITCH, this.indent_switchstatements_compare_to_switch ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
options.put(DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE, Integer.toString(this.indentation_size));
// options.put(CodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_AFTER_OPENING_BRACE_IN_ARRAY_INITIALIZER, this.insert_new_line_after_opening_brace_in_array_initializer? CCorePlugin.INSERT : CCorePlugin.DO_NOT_INSERT);
// options.put(CodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_AT_END_OF_FILE_IF_MISSING, this.insert_new_line_at_end_of_file_if_missing ? CCorePlugin.INSERT : CCorePlugin.DO_NOT_INSERT);
// options.put(CodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_BEFORE_CATCH_IN_TRY_STATEMENT, this.insert_new_line_before_catch_in_try_statement? CCorePlugin.INSERT : CCorePlugin.DO_NOT_INSERT);
@ -511,22 +514,22 @@ public class DefaultCodeFormatterOptions {
// options.put(CodeFormatterConstants.FORMATTER_LINE_SPLIT, Integer.toString(this.page_width));
switch(this.tab_char) {
case SPACE :
options.put(CodeFormatterConstants.FORMATTER_TAB_CHAR, CCorePlugin.SPACE);
options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, CCorePlugin.SPACE);
break;
case TAB :
options.put(CodeFormatterConstants.FORMATTER_TAB_CHAR, CCorePlugin.TAB);
options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, CCorePlugin.TAB);
break;
case MIXED :
options.put(CodeFormatterConstants.FORMATTER_TAB_CHAR, CodeFormatterConstants.MIXED);
options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, DefaultCodeFormatterConstants.MIXED);
break;
}
options.put(CodeFormatterConstants.FORMATTER_TAB_SIZE, Integer.toString(this.tab_size));
options.put(CodeFormatterConstants.FORMATTER_USE_TABS_ONLY_FOR_LEADING_INDENTATIONS, this.use_tabs_only_for_leading_indentations ? CodeFormatterConstants.TRUE : CodeFormatterConstants.FALSE);
options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, Integer.toString(this.tab_size));
options.put(DefaultCodeFormatterConstants.FORMATTER_USE_TABS_ONLY_FOR_LEADING_INDENTATIONS, this.use_tabs_only_for_leading_indentations ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
return options;
}
public void set(Map settings) {
final Object alignmentForArgumentsInAllocationExpressionOption = settings.get(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_ALLOCATION_EXPRESSION);
final Object alignmentForArgumentsInAllocationExpressionOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_ALLOCATION_EXPRESSION);
if (alignmentForArgumentsInAllocationExpressionOption != null) {
try {
this.alignment_for_arguments_in_allocation_expression = Integer.parseInt((String) alignmentForArgumentsInAllocationExpressionOption);
@ -536,7 +539,7 @@ public class DefaultCodeFormatterOptions {
this.alignment_for_arguments_in_allocation_expression = Alignment.M_COMPACT_SPLIT;
}
}
final Object alignmentForArgumentsInEnumConstantOption = settings.get(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_ENUM_CONSTANT);
final Object alignmentForArgumentsInEnumConstantOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_ENUM_CONSTANT);
if (alignmentForArgumentsInEnumConstantOption != null) {
try {
this.alignment_for_arguments_in_enum_constant = Integer.parseInt((String) alignmentForArgumentsInEnumConstantOption);
@ -546,7 +549,7 @@ public class DefaultCodeFormatterOptions {
this.alignment_for_arguments_in_enum_constant = Alignment.M_COMPACT_SPLIT;
}
}
final Object alignmentForArgumentsInExplicitConstructorCallOption = settings.get(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_EXPLICIT_CONSTRUCTOR_CALL);
final Object alignmentForArgumentsInExplicitConstructorCallOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_EXPLICIT_CONSTRUCTOR_CALL);
if (alignmentForArgumentsInExplicitConstructorCallOption != null) {
try {
this.alignment_for_arguments_in_explicit_constructor_call = Integer.parseInt((String) alignmentForArgumentsInExplicitConstructorCallOption);
@ -556,7 +559,7 @@ public class DefaultCodeFormatterOptions {
this.alignment_for_arguments_in_explicit_constructor_call = Alignment.M_COMPACT_SPLIT;
}
}
final Object alignmentForArgumentsInMethodInvocationOption = settings.get(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION);
final Object alignmentForArgumentsInMethodInvocationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION);
if (alignmentForArgumentsInMethodInvocationOption != null) {
try {
this.alignment_for_arguments_in_method_invocation = Integer.parseInt((String) alignmentForArgumentsInMethodInvocationOption);
@ -566,7 +569,7 @@ public class DefaultCodeFormatterOptions {
this.alignment_for_arguments_in_method_invocation = Alignment.M_COMPACT_SPLIT;
}
}
final Object alignmentForArgumentsInQualifiedAllocationExpressionOption = settings.get(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_QUALIFIED_ALLOCATION_EXPRESSION);
final Object alignmentForArgumentsInQualifiedAllocationExpressionOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_QUALIFIED_ALLOCATION_EXPRESSION);
if (alignmentForArgumentsInQualifiedAllocationExpressionOption != null) {
try {
this.alignment_for_arguments_in_qualified_allocation_expression = Integer.parseInt((String) alignmentForArgumentsInQualifiedAllocationExpressionOption);
@ -576,7 +579,7 @@ public class DefaultCodeFormatterOptions {
this.alignment_for_arguments_in_qualified_allocation_expression = Alignment.M_COMPACT_SPLIT;
}
}
final Object alignmentForAssignmentOption = settings.get(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ASSIGNMENT);
final Object alignmentForAssignmentOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ASSIGNMENT);
if (alignmentForAssignmentOption != null) {
try {
this.alignment_for_assignment = Integer.parseInt((String) alignmentForAssignmentOption);
@ -586,7 +589,7 @@ public class DefaultCodeFormatterOptions {
this.alignment_for_assignment = Alignment.M_ONE_PER_LINE_SPLIT;
}
}
final Object alignmentForBinaryExpressionOption = settings.get(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_BINARY_EXPRESSION);
final Object alignmentForBinaryExpressionOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_BINARY_EXPRESSION);
if (alignmentForBinaryExpressionOption != null) {
try {
this.alignment_for_binary_expression = Integer.parseInt((String) alignmentForBinaryExpressionOption);
@ -596,7 +599,7 @@ public class DefaultCodeFormatterOptions {
this.alignment_for_binary_expression = Alignment.M_COMPACT_SPLIT;
}
}
final Object alignmentForCompactIfOption = settings.get(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_COMPACT_IF);
final Object alignmentForCompactIfOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_COMPACT_IF);
if (alignmentForCompactIfOption != null) {
try {
this.alignment_for_compact_if = Integer.parseInt((String) alignmentForCompactIfOption);
@ -606,7 +609,7 @@ public class DefaultCodeFormatterOptions {
this.alignment_for_compact_if = Alignment.M_ONE_PER_LINE_SPLIT | Alignment.M_INDENT_BY_ONE;
}
}
final Object alignmentForConditionalExpressionOption = settings.get(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_CONDITIONAL_EXPRESSION);
final Object alignmentForConditionalExpressionOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_CONDITIONAL_EXPRESSION);
if (alignmentForConditionalExpressionOption != null) {
try {
this.alignment_for_conditional_expression = Integer.parseInt((String) alignmentForConditionalExpressionOption);
@ -616,7 +619,7 @@ public class DefaultCodeFormatterOptions {
this.alignment_for_conditional_expression = Alignment.M_ONE_PER_LINE_SPLIT;
}
}
final Object alignmentForEnumConstantsOption = settings.get(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ENUM_CONSTANTS);
final Object alignmentForEnumConstantsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ENUM_CONSTANTS);
if (alignmentForEnumConstantsOption != null) {
try {
this.alignment_for_enum_constants = Integer.parseInt((String) alignmentForEnumConstantsOption);
@ -626,7 +629,7 @@ public class DefaultCodeFormatterOptions {
this.alignment_for_enum_constants = Alignment.NONE;
}
}
final Object alignmentForExpressionsInArrayInitializerOption = settings.get(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_ARRAY_INITIALIZER);
final Object alignmentForExpressionsInArrayInitializerOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_ARRAY_INITIALIZER);
if (alignmentForExpressionsInArrayInitializerOption != null) {
try {
this.alignment_for_expressions_in_array_initializer = Integer.parseInt((String) alignmentForExpressionsInArrayInitializerOption);
@ -636,7 +639,7 @@ public class DefaultCodeFormatterOptions {
this.alignment_for_expressions_in_array_initializer = Alignment.M_COMPACT_SPLIT;
}
}
final Object alignmentForMultipleFieldsOption = settings.get(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_MULTIPLE_FIELDS);
final Object alignmentForMultipleFieldsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_MULTIPLE_FIELDS);
if (alignmentForMultipleFieldsOption != null) {
try {
this.alignment_for_multiple_fields = Integer.parseInt((String) alignmentForMultipleFieldsOption);
@ -646,7 +649,7 @@ public class DefaultCodeFormatterOptions {
this.alignment_for_multiple_fields = Alignment.M_COMPACT_SPLIT;
}
}
final Object alignmentForParametersInConstructorDeclarationOption = settings.get(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_CONSTRUCTOR_DECLARATION);
final Object alignmentForParametersInConstructorDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_CONSTRUCTOR_DECLARATION);
if (alignmentForParametersInConstructorDeclarationOption != null) {
try {
this.alignment_for_parameters_in_constructor_declaration = Integer.parseInt((String) alignmentForParametersInConstructorDeclarationOption);
@ -656,7 +659,7 @@ public class DefaultCodeFormatterOptions {
this.alignment_for_parameters_in_constructor_declaration = Alignment.M_COMPACT_SPLIT;
}
}
final Object alignmentForParametersInMethodDeclarationOption = settings.get(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION);
final Object alignmentForParametersInMethodDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION);
if (alignmentForParametersInMethodDeclarationOption != null) {
try {
this.alignment_for_parameters_in_method_declaration = Integer.parseInt((String) alignmentForParametersInMethodDeclarationOption);
@ -666,7 +669,7 @@ public class DefaultCodeFormatterOptions {
this.alignment_for_parameters_in_method_declaration = Alignment.M_COMPACT_SPLIT;
}
}
final Object alignmentForSelectorInMethodInvocationOption = settings.get(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SELECTOR_IN_METHOD_INVOCATION);
final Object alignmentForSelectorInMethodInvocationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SELECTOR_IN_METHOD_INVOCATION);
if (alignmentForSelectorInMethodInvocationOption != null) {
try {
this.alignment_for_selector_in_method_invocation = Integer.parseInt((String) alignmentForSelectorInMethodInvocationOption);
@ -676,7 +679,7 @@ public class DefaultCodeFormatterOptions {
this.alignment_for_selector_in_method_invocation = Alignment.M_COMPACT_SPLIT;
}
}
final Object alignmentForSuperclassInTypeDeclarationOption = settings.get(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SUPERCLASS_IN_TYPE_DECLARATION);
final Object alignmentForSuperclassInTypeDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SUPERCLASS_IN_TYPE_DECLARATION);
if (alignmentForSuperclassInTypeDeclarationOption != null) {
try {
this.alignment_for_superclass_in_type_declaration = Integer.parseInt((String) alignmentForSuperclassInTypeDeclarationOption);
@ -686,7 +689,7 @@ public class DefaultCodeFormatterOptions {
this.alignment_for_superclass_in_type_declaration = Alignment.M_NEXT_SHIFTED_SPLIT;
}
}
final Object alignmentForSuperinterfacesInEnumDeclarationOption = settings.get(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SUPERINTERFACES_IN_ENUM_DECLARATION);
final Object alignmentForSuperinterfacesInEnumDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SUPERINTERFACES_IN_ENUM_DECLARATION);
if (alignmentForSuperinterfacesInEnumDeclarationOption != null) {
try {
this.alignment_for_superinterfaces_in_enum_declaration = Integer.parseInt((String) alignmentForSuperinterfacesInEnumDeclarationOption);
@ -696,7 +699,7 @@ public class DefaultCodeFormatterOptions {
this.alignment_for_superinterfaces_in_enum_declaration = Alignment.M_NEXT_SHIFTED_SPLIT;
}
}
final Object alignmentForSuperinterfacesInTypeDeclarationOption = settings.get(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SUPERINTERFACES_IN_TYPE_DECLARATION);
final Object alignmentForSuperinterfacesInTypeDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SUPERINTERFACES_IN_TYPE_DECLARATION);
if (alignmentForSuperinterfacesInTypeDeclarationOption != null) {
try {
this.alignment_for_superinterfaces_in_type_declaration = Integer.parseInt((String) alignmentForSuperinterfacesInTypeDeclarationOption);
@ -706,7 +709,7 @@ public class DefaultCodeFormatterOptions {
this.alignment_for_superinterfaces_in_type_declaration = Alignment.M_NEXT_SHIFTED_SPLIT;
}
}
final Object alignmentForThrowsClauseInConstructorDeclarationOption = settings.get(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_THROWS_CLAUSE_IN_CONSTRUCTOR_DECLARATION);
final Object alignmentForThrowsClauseInConstructorDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_THROWS_CLAUSE_IN_CONSTRUCTOR_DECLARATION);
if (alignmentForThrowsClauseInConstructorDeclarationOption != null) {
try {
this.alignment_for_throws_clause_in_constructor_declaration = Integer.parseInt((String) alignmentForThrowsClauseInConstructorDeclarationOption);
@ -716,7 +719,7 @@ public class DefaultCodeFormatterOptions {
this.alignment_for_throws_clause_in_constructor_declaration = Alignment.M_COMPACT_SPLIT;
}
}
final Object alignmentForThrowsClauseInMethodDeclarationOption = settings.get(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_THROWS_CLAUSE_IN_METHOD_DECLARATION);
final Object alignmentForThrowsClauseInMethodDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_THROWS_CLAUSE_IN_METHOD_DECLARATION);
if (alignmentForThrowsClauseInMethodDeclarationOption != null) {
try {
this.alignment_for_throws_clause_in_method_declaration = Integer.parseInt((String) alignmentForThrowsClauseInMethodDeclarationOption);
@ -726,83 +729,83 @@ public class DefaultCodeFormatterOptions {
this.alignment_for_throws_clause_in_method_declaration = Alignment.M_COMPACT_SPLIT;
}
}
final Object alignTypeMembersOnColumnsOption = settings.get(CodeFormatterConstants.FORMATTER_ALIGN_TYPE_MEMBERS_ON_COLUMNS);
final Object alignTypeMembersOnColumnsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGN_TYPE_MEMBERS_ON_COLUMNS);
if (alignTypeMembersOnColumnsOption != null) {
this.align_type_members_on_columns = CodeFormatterConstants.TRUE.equals(alignTypeMembersOnColumnsOption);
this.align_type_members_on_columns = DefaultCodeFormatterConstants.TRUE.equals(alignTypeMembersOnColumnsOption);
}
final Object bracePositionForArrayInitializerOption = settings.get(CodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ARRAY_INITIALIZER);
final Object bracePositionForArrayInitializerOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ARRAY_INITIALIZER);
if (bracePositionForArrayInitializerOption != null) {
try {
this.brace_position_for_array_initializer = (String) bracePositionForArrayInitializerOption;
} catch(ClassCastException e) {
this.brace_position_for_array_initializer = CodeFormatterConstants.END_OF_LINE;
this.brace_position_for_array_initializer = DefaultCodeFormatterConstants.END_OF_LINE;
}
}
final Object bracePositionForBlockOption = settings.get(CodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_BLOCK);
final Object bracePositionForBlockOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_BLOCK);
if (bracePositionForBlockOption != null) {
try {
this.brace_position_for_block = (String) bracePositionForBlockOption;
} catch(ClassCastException e) {
this.brace_position_for_block = CodeFormatterConstants.END_OF_LINE;
this.brace_position_for_block = DefaultCodeFormatterConstants.END_OF_LINE;
}
}
final Object bracePositionForBlockInCaseOption = settings.get(CodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_BLOCK_IN_CASE);
final Object bracePositionForBlockInCaseOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_BLOCK_IN_CASE);
if (bracePositionForBlockInCaseOption != null) {
try {
this.brace_position_for_block_in_case = (String) bracePositionForBlockInCaseOption;
} catch(ClassCastException e) {
this.brace_position_for_block_in_case = CodeFormatterConstants.END_OF_LINE;
this.brace_position_for_block_in_case = DefaultCodeFormatterConstants.END_OF_LINE;
}
}
final Object bracePositionForConstructorDeclarationOption = settings.get(CodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_CONSTRUCTOR_DECLARATION);
final Object bracePositionForConstructorDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_CONSTRUCTOR_DECLARATION);
if (bracePositionForConstructorDeclarationOption != null) {
try {
this.brace_position_for_constructor_declaration = (String) bracePositionForConstructorDeclarationOption;
} catch(ClassCastException e) {
this.brace_position_for_constructor_declaration = CodeFormatterConstants.END_OF_LINE;
this.brace_position_for_constructor_declaration = DefaultCodeFormatterConstants.END_OF_LINE;
}
}
final Object bracePositionForEnumConstantOption = settings.get(CodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ENUM_CONSTANT);
final Object bracePositionForEnumConstantOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ENUM_CONSTANT);
if (bracePositionForEnumConstantOption != null) {
try {
this.brace_position_for_enum_constant = (String) bracePositionForEnumConstantOption;
} catch(ClassCastException e) {
this.brace_position_for_enum_constant = CodeFormatterConstants.END_OF_LINE;
this.brace_position_for_enum_constant = DefaultCodeFormatterConstants.END_OF_LINE;
}
}
final Object bracePositionForEnumDeclarationOption = settings.get(CodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ENUM_DECLARATION);
final Object bracePositionForEnumDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ENUM_DECLARATION);
if (bracePositionForEnumDeclarationOption != null) {
try {
this.brace_position_for_enum_declaration = (String) bracePositionForEnumDeclarationOption;
} catch(ClassCastException e) {
this.brace_position_for_enum_declaration = CodeFormatterConstants.END_OF_LINE;
this.brace_position_for_enum_declaration = DefaultCodeFormatterConstants.END_OF_LINE;
}
}
final Object bracePositionForMethodDeclarationOption = settings.get(CodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION);
final Object bracePositionForMethodDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION);
if (bracePositionForMethodDeclarationOption != null) {
try {
this.brace_position_for_method_declaration = (String) bracePositionForMethodDeclarationOption;
} catch(ClassCastException e) {
this.brace_position_for_method_declaration = CodeFormatterConstants.END_OF_LINE;
this.brace_position_for_method_declaration = DefaultCodeFormatterConstants.END_OF_LINE;
}
}
final Object bracePositionForSwitchOption = settings.get(CodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_SWITCH);
final Object bracePositionForSwitchOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_SWITCH);
if (bracePositionForSwitchOption != null) {
try {
this.brace_position_for_switch = (String) bracePositionForSwitchOption;
} catch(ClassCastException e) {
this.brace_position_for_switch = CodeFormatterConstants.END_OF_LINE;
this.brace_position_for_switch = DefaultCodeFormatterConstants.END_OF_LINE;
}
}
final Object bracePositionForTypeDeclarationOption = settings.get(CodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION);
final Object bracePositionForTypeDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION);
if (bracePositionForTypeDeclarationOption != null) {
try {
this.brace_position_for_type_declaration = (String) bracePositionForTypeDeclarationOption;
} catch(ClassCastException e) {
this.brace_position_for_type_declaration = CodeFormatterConstants.END_OF_LINE;
this.brace_position_for_type_declaration = DefaultCodeFormatterConstants.END_OF_LINE;
}
}
final Object continuationIndentationOption = settings.get(CodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION);
final Object continuationIndentationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION);
if (continuationIndentationOption != null) {
try {
this.continuation_indentation = Integer.parseInt((String) continuationIndentationOption);
@ -812,7 +815,7 @@ public class DefaultCodeFormatterOptions {
this.continuation_indentation = 2;
}
}
final Object continuationIndentationForArrayInitializerOption = settings.get(CodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION_FOR_ARRAY_INITIALIZER);
final Object continuationIndentationForArrayInitializerOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION_FOR_ARRAY_INITIALIZER);
if (continuationIndentationForArrayInitializerOption != null) {
try {
this.continuation_indentation_for_array_initializer = Integer.parseInt((String) continuationIndentationForArrayInitializerOption);
@ -962,43 +965,47 @@ public class DefaultCodeFormatterOptions {
// this.comment_line_length = 80;
// }
// }
final Object indentStatementsCompareToBlockOption = settings.get(CodeFormatterConstants.FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BLOCK);
final Object indentStatementsCompareToBlockOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BLOCK);
if (indentStatementsCompareToBlockOption != null) {
this.indent_statements_compare_to_block = CodeFormatterConstants.TRUE.equals(indentStatementsCompareToBlockOption);
this.indent_statements_compare_to_block = DefaultCodeFormatterConstants.TRUE.equals(indentStatementsCompareToBlockOption);
}
final Object indentStatementsCompareToBodyOption = settings.get(CodeFormatterConstants.FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BODY);
final Object indentStatementsCompareToBodyOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BODY);
if (indentStatementsCompareToBodyOption != null) {
this.indent_statements_compare_to_body = CodeFormatterConstants.TRUE.equals(indentStatementsCompareToBodyOption);
this.indent_statements_compare_to_body = DefaultCodeFormatterConstants.TRUE.equals(indentStatementsCompareToBodyOption);
}
final Object indentBodyDeclarationsCompareToEnumConstantHeaderOption = settings.get(CodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ENUM_CONSTANT_HEADER);
final Object indentBodyDeclarationsCompareToEnumConstantHeaderOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ENUM_CONSTANT_HEADER);
if (indentBodyDeclarationsCompareToEnumConstantHeaderOption != null) {
this.indent_body_declarations_compare_to_enum_constant_header = CodeFormatterConstants.TRUE.equals(indentBodyDeclarationsCompareToEnumConstantHeaderOption);
this.indent_body_declarations_compare_to_enum_constant_header = DefaultCodeFormatterConstants.TRUE.equals(indentBodyDeclarationsCompareToEnumConstantHeaderOption);
}
final Object indentBodyDeclarationsCompareToEnumDeclarationHeaderOption = settings.get(CodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ENUM_DECLARATION_HEADER);
final Object indentBodyDeclarationsCompareToEnumDeclarationHeaderOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ENUM_DECLARATION_HEADER);
if (indentBodyDeclarationsCompareToEnumDeclarationHeaderOption != null) {
this.indent_body_declarations_compare_to_enum_declaration_header = CodeFormatterConstants.TRUE.equals(indentBodyDeclarationsCompareToEnumDeclarationHeaderOption);
this.indent_body_declarations_compare_to_enum_declaration_header = DefaultCodeFormatterConstants.TRUE.equals(indentBodyDeclarationsCompareToEnumDeclarationHeaderOption);
}
final Object indentBodyDeclarationsCompareToTypeHeaderOption = settings.get(CodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_TYPE_HEADER);
if (indentBodyDeclarationsCompareToTypeHeaderOption != null) {
this.indent_body_declarations_compare_to_type_header = CodeFormatterConstants.TRUE.equals(indentBodyDeclarationsCompareToTypeHeaderOption);
final Object indentAccessSpecifierCompareToTypeHeaderOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INDENT_ACCESS_SPECIFIER_COMPARE_TO_TYPE_HEADER);
if (indentAccessSpecifierCompareToTypeHeaderOption != null) {
this.indent_access_specifier_compare_to_type_header = DefaultCodeFormatterConstants.TRUE.equals(indentAccessSpecifierCompareToTypeHeaderOption);
}
final Object indentBreaksCompareToCasesOption = settings.get(CodeFormatterConstants.FORMATTER_INDENT_BREAKS_COMPARE_TO_CASES);
final Object indentBodyDeclarationsCompareToAccessSpecifierOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ACCESS_SPECIFIER);
if (indentBodyDeclarationsCompareToAccessSpecifierOption != null) {
this.indent_body_declarations_compare_to_access_specifier = DefaultCodeFormatterConstants.TRUE.equals(indentBodyDeclarationsCompareToAccessSpecifierOption);
}
final Object indentBreaksCompareToCasesOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INDENT_BREAKS_COMPARE_TO_CASES);
if (indentBreaksCompareToCasesOption != null) {
this.indent_breaks_compare_to_cases = CodeFormatterConstants.TRUE.equals(indentBreaksCompareToCasesOption);
this.indent_breaks_compare_to_cases = DefaultCodeFormatterConstants.TRUE.equals(indentBreaksCompareToCasesOption);
}
final Object indentEmptyLinesOption = settings.get(CodeFormatterConstants.FORMATTER_INDENT_EMPTY_LINES);
final Object indentEmptyLinesOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INDENT_EMPTY_LINES);
if (indentEmptyLinesOption != null) {
this.indent_empty_lines = CodeFormatterConstants.TRUE.equals(indentEmptyLinesOption);
this.indent_empty_lines = DefaultCodeFormatterConstants.TRUE.equals(indentEmptyLinesOption);
}
final Object indentSwitchstatementsCompareToCasesOption = settings.get(CodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_CASES);
final Object indentSwitchstatementsCompareToCasesOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_CASES);
if (indentSwitchstatementsCompareToCasesOption != null) {
this.indent_switchstatements_compare_to_cases = CodeFormatterConstants.TRUE.equals(indentSwitchstatementsCompareToCasesOption);
this.indent_switchstatements_compare_to_cases = DefaultCodeFormatterConstants.TRUE.equals(indentSwitchstatementsCompareToCasesOption);
}
final Object indentSwitchstatementsCompareToSwitchOption = settings.get(CodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_SWITCH);
final Object indentSwitchstatementsCompareToSwitchOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_SWITCH);
if (indentSwitchstatementsCompareToSwitchOption != null) {
this.indent_switchstatements_compare_to_switch = CodeFormatterConstants.TRUE.equals(indentSwitchstatementsCompareToSwitchOption);
this.indent_switchstatements_compare_to_switch = DefaultCodeFormatterConstants.TRUE.equals(indentSwitchstatementsCompareToSwitchOption);
}
final Object indentationSizeOption = settings.get(CodeFormatterConstants.FORMATTER_INDENTATION_SIZE);
final Object indentationSizeOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE);
if (indentationSizeOption != null) {
try {
this.indentation_size = Integer.parseInt((String) indentationSizeOption);
@ -1658,7 +1665,7 @@ public class DefaultCodeFormatterOptions {
// if (putEmptyStatementOnNewLineOption != null) {
// this.put_empty_statement_on_new_line = CodeFormatterConstants.TRUE.equals(putEmptyStatementOnNewLineOption);
// }
final Object tabSizeOption = settings.get(CodeFormatterConstants.FORMATTER_TAB_SIZE);
final Object tabSizeOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE);
if (tabSizeOption != null) {
try {
this.tab_size = Integer.parseInt((String) tabSizeOption);
@ -1668,11 +1675,11 @@ public class DefaultCodeFormatterOptions {
this.tab_size = 4;
}
}
final Object useTabsOnlyForLeadingIndentationsOption = settings.get(CodeFormatterConstants.FORMATTER_USE_TABS_ONLY_FOR_LEADING_INDENTATIONS);
final Object useTabsOnlyForLeadingIndentationsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_USE_TABS_ONLY_FOR_LEADING_INDENTATIONS);
if (useTabsOnlyForLeadingIndentationsOption != null) {
this.use_tabs_only_for_leading_indentations = CodeFormatterConstants.TRUE.equals(useTabsOnlyForLeadingIndentationsOption);
this.use_tabs_only_for_leading_indentations = DefaultCodeFormatterConstants.TRUE.equals(useTabsOnlyForLeadingIndentationsOption);
}
final Object pageWidthOption = settings.get(CodeFormatterConstants.FORMATTER_LINE_SPLIT);
final Object pageWidthOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_LINE_SPLIT);
if (pageWidthOption != null) {
try {
this.page_width = Integer.parseInt((String) pageWidthOption);
@ -1682,7 +1689,7 @@ public class DefaultCodeFormatterOptions {
this.page_width = 80;
}
}
final Object useTabOption = settings.get(CodeFormatterConstants.FORMATTER_TAB_CHAR);
final Object useTabOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR);
if (useTabOption != null) {
if (CCorePlugin.TAB.equals(useTabOption)) {
this.tab_char = TAB;
@ -1716,15 +1723,15 @@ public class DefaultCodeFormatterOptions {
this.alignment_for_throws_clause_in_constructor_declaration = Alignment.M_COMPACT_SPLIT;
this.alignment_for_throws_clause_in_method_declaration = Alignment.M_COMPACT_SPLIT;
this.align_type_members_on_columns = false;
this.brace_position_for_array_initializer = CodeFormatterConstants.END_OF_LINE;
this.brace_position_for_block = CodeFormatterConstants.END_OF_LINE;
this.brace_position_for_block_in_case = CodeFormatterConstants.END_OF_LINE;
this.brace_position_for_constructor_declaration = CodeFormatterConstants.END_OF_LINE;
this.brace_position_for_enum_constant = CodeFormatterConstants.END_OF_LINE;
this.brace_position_for_enum_declaration = CodeFormatterConstants.END_OF_LINE;
this.brace_position_for_method_declaration = CodeFormatterConstants.END_OF_LINE;
this.brace_position_for_type_declaration = CodeFormatterConstants.END_OF_LINE;
this.brace_position_for_switch = CodeFormatterConstants.END_OF_LINE;
this.brace_position_for_array_initializer = DefaultCodeFormatterConstants.END_OF_LINE;
this.brace_position_for_block = DefaultCodeFormatterConstants.END_OF_LINE;
this.brace_position_for_block_in_case = DefaultCodeFormatterConstants.END_OF_LINE;
this.brace_position_for_constructor_declaration = DefaultCodeFormatterConstants.END_OF_LINE;
this.brace_position_for_enum_constant = DefaultCodeFormatterConstants.END_OF_LINE;
this.brace_position_for_enum_declaration = DefaultCodeFormatterConstants.END_OF_LINE;
this.brace_position_for_method_declaration = DefaultCodeFormatterConstants.END_OF_LINE;
this.brace_position_for_type_declaration = DefaultCodeFormatterConstants.END_OF_LINE;
this.brace_position_for_switch = DefaultCodeFormatterConstants.END_OF_LINE;
// this.comment_clear_blank_lines = false;
// this.comment_format = true;
// this.comment_format_header = false;
@ -1752,7 +1759,7 @@ public class DefaultCodeFormatterOptions {
this.indent_statements_compare_to_body = true;
this.indent_body_declarations_compare_to_enum_constant_header = true;
this.indent_body_declarations_compare_to_enum_declaration_header = true;
this.indent_body_declarations_compare_to_type_header = true;
this.indent_body_declarations_compare_to_access_specifier = true;
this.indent_breaks_compare_to_cases = true;
this.indent_empty_lines = false;
this.indent_switchstatements_compare_to_cases = true;
@ -1947,15 +1954,15 @@ public class DefaultCodeFormatterOptions {
this.alignment_for_throws_clause_in_constructor_declaration = Alignment.M_COMPACT_SPLIT;
this.alignment_for_throws_clause_in_method_declaration = Alignment.M_COMPACT_SPLIT;
this.align_type_members_on_columns = false;
this.brace_position_for_array_initializer = CodeFormatterConstants.END_OF_LINE;
this.brace_position_for_block = CodeFormatterConstants.END_OF_LINE;
this.brace_position_for_block_in_case = CodeFormatterConstants.END_OF_LINE;
this.brace_position_for_constructor_declaration = CodeFormatterConstants.END_OF_LINE;
this.brace_position_for_enum_constant = CodeFormatterConstants.END_OF_LINE;
this.brace_position_for_enum_declaration = CodeFormatterConstants.END_OF_LINE;
this.brace_position_for_method_declaration = CodeFormatterConstants.END_OF_LINE;
this.brace_position_for_type_declaration = CodeFormatterConstants.END_OF_LINE;
this.brace_position_for_switch = CodeFormatterConstants.END_OF_LINE;
this.brace_position_for_array_initializer = DefaultCodeFormatterConstants.END_OF_LINE;
this.brace_position_for_block = DefaultCodeFormatterConstants.END_OF_LINE;
this.brace_position_for_block_in_case = DefaultCodeFormatterConstants.END_OF_LINE;
this.brace_position_for_constructor_declaration = DefaultCodeFormatterConstants.END_OF_LINE;
this.brace_position_for_enum_constant = DefaultCodeFormatterConstants.END_OF_LINE;
this.brace_position_for_enum_declaration = DefaultCodeFormatterConstants.END_OF_LINE;
this.brace_position_for_method_declaration = DefaultCodeFormatterConstants.END_OF_LINE;
this.brace_position_for_type_declaration = DefaultCodeFormatterConstants.END_OF_LINE;
this.brace_position_for_switch = DefaultCodeFormatterConstants.END_OF_LINE;
// this.comment_clear_blank_lines = false;
// this.comment_format = true;
// this.comment_format_header = false;
@ -1983,7 +1990,7 @@ public class DefaultCodeFormatterOptions {
this.indent_statements_compare_to_body = true;
this.indent_body_declarations_compare_to_enum_constant_header = true;
this.indent_body_declarations_compare_to_enum_declaration_header = true;
this.indent_body_declarations_compare_to_type_header = true;
this.indent_body_declarations_compare_to_access_specifier = true;
this.indent_breaks_compare_to_cases = true;
this.indent_empty_lines = false;
this.indent_switchstatements_compare_to_cases = true;

View file

@ -7,6 +7,7 @@
*
* Contributors:
* Anton Leherbauer (Wind River Systems) - initial API and implementation
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.ui.tests.text;
@ -111,6 +112,7 @@ public class CAutoIndentTest extends TestCase {
backspace();
}
}
public void backspace() throws BadLocationException {
TestDocumentCommand command = new TestDocumentCommand(fCaretOffset - 1, 1, ""); //$NON-NLS-1$
customizeDocumentCommand(command);
@ -140,6 +142,19 @@ public class CAutoIndentTest extends TestCase {
return setCaretOffset(fCaretOffset + shift);
}
public int goTo(int line) throws BadLocationException {
fCaretOffset = fDoc.getLineOffset(line);
return fCaretOffset;
}
public int goTo(int line, int column) throws BadLocationException {
if (column < 0 || column > fDoc.getLineLength(line)) {
throw new BadLocationException("No column " + column + " in line " + line); //$NON-NLS-1$ $NON-NLS-2$
}
fCaretOffset = fDoc.getLineOffset(line) + column;
return fCaretOffset;
}
public int getCaretLine() throws BadLocationException {
return fDoc.getLineOfOffset(fCaretOffset);
}
@ -271,6 +286,33 @@ public class CAutoIndentTest extends TestCase {
assertEquals("\t\tint x = 5;", tester.getLine(1)); //$NON-NLS-1$
}
public void testPasteAutoIndent() throws IOException, CoreException, BadLocationException {
AutoEditTester tester = createAutoEditTester(); //$NON-NLS-1$
tester.type("class A {\n"); //$NON-NLS-1$
tester.goTo(1, 0);
tester.paste("class B {\n" +
"protected:\n" +
"\tB();\n" +
"public:\n" +
"\tint getX() const {\n" +
"\t\treturn x_;\n" +
"\t}\n" +
"private:\n" +
"\tint x_;\n" +
"};\n"); //$NON-NLS-1$
tester.goTo(1, 0);
assertEquals("\tclass B {", tester.getLine(0)); //$NON-NLS-1$
assertEquals("\tprotected:", tester.getLine(1)); //$NON-NLS-1$
assertEquals("\t\tB();", tester.getLine(2)); //$NON-NLS-1$
assertEquals("\tpublic:", tester.getLine(3)); //$NON-NLS-1$
assertEquals("\t\tint getX() const {", tester.getLine(4)); //$NON-NLS-1$
assertEquals("\t\t\treturn x_;", tester.getLine(5)); //$NON-NLS-1$
assertEquals("\t\t}", tester.getLine(6)); //$NON-NLS-1$
assertEquals("\tprivate:", tester.getLine(7)); //$NON-NLS-1$
assertEquals("\t\tint x_;", tester.getLine(8)); //$NON-NLS-1$
assertEquals("\t};", tester.getLine(9)); //$NON-NLS-1$
}
public void testDefaultAutoIndent() throws IOException, CoreException, BadLocationException {
AutoEditTester tester = createAutoEditTester(); //$NON-NLS-1$
tester.type(" initial indent=3\n"); //$NON-NLS-1$

View file

@ -113,6 +113,9 @@ ActionDefinition.addBlockComment.description= Enclose the selection with a block
ActionDefinition.removeBlockComment.name= Remove Block Comment
ActionDefinition.removeBlockComment.description= Remove the block comment enclosing the selection
ActionDefinition.indent.name= Indent Line
ActionDefinition.indent.description=Indents the current line
ActionDefinition.joinLines.name= Join Lines
ActionDefinition.joinLines.description= Join the current and next line together
@ -132,8 +135,9 @@ CPluginEditorPreferencePage.name=Editor
CPluginTemplatePreferencePage.name=Templates
CPluginBuildConsolePreferencePage.name=Build Console
CPluginFileTypesPreferencePage.name=File Types
CodeFormatterPreferencePage.name=Code Formatter
CodeFormatterPreferencePage.name=Code Style
CodeAssistPreferencePage.name=Content Assist
SmartTypingPreferencePage.name=Typing
ColoringPreferencePage.name=Syntax Coloring
todoPageName=C/C++ Task Tags

View file

@ -583,6 +583,12 @@
class="org.eclipse.cdt.internal.ui.preferences.CTemplatePreferencePage"
id="org.eclipse.cdt.ui.preferences.TemplatePreferencePage">
</page>
<page
name="%SmartTypingPreferencePage.name"
category="org.eclipse.cdt.ui.preferences.CEditorPreferencePage"
class="org.eclipse.cdt.internal.ui.preferences.SmartTypingPreferencePage"
id="org.eclipse.cdt.ui.preferences.SmartTypingPreferencePage">
</page>
<page
name="%CodeFormatterPreferencePage.name"
category="org.eclipse.cdt.ui.preferences.CPluginPreferencePage"
@ -882,6 +888,11 @@
contextId="org.eclipse.cdt.ui.cEditorScope"
commandId="org.eclipse.cdt.ui.edit.text.c.remove.block.comment"
schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"/>
<key
sequence="M1+I"
contextId="org.eclipse.cdt.ui.cEditorScope"
commandId="org.eclipse.cdt.ui.edit.text.c.indent"
schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"/>
<key
sequence="M1+M3+H"
contextId="org.eclipse.cdt.ui.cEditorScope"
@ -991,6 +1002,12 @@
categoryId="org.eclipse.cdt.ui.category.source"
id="org.eclipse.cdt.ui.edit.text.c.remove.block.comment">
</command>
<command
name="%ActionDefinition.indent.name"
description="%ActionDefinition.indent.description"
categoryId="org.eclipse.cdt.ui.category.source"
id="org.eclipse.cdt.ui.edit.text.c.indent">
</command>
<command
name="%ActionDefinition.joinLines.name"
description="%ActionDefinition.joinLines.description"

View file

@ -11,15 +11,18 @@
*******************************************************************************/
package org.eclipse.cdt.internal.corext.template.c;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.internal.corext.util.CodeFormatterUtil;
import org.eclipse.cdt.internal.ui.util.Strings;
import org.eclipse.cdt.ui.CUIPlugin;
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.TextUtilities;
import org.eclipse.jface.text.templates.Template;
import org.eclipse.jface.text.templates.TemplateBuffer;
import org.eclipse.jface.text.templates.TemplateContextType;
@ -27,7 +30,6 @@ import org.eclipse.jface.text.templates.TemplateException;
import org.eclipse.jface.text.templates.TemplateTranslator;
/**
* A context for c/c++
*/
@ -148,27 +150,25 @@ public class CContext extends TranslationUnitContext {
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());
ICProject project= getTranslationUnit() != null ? getTranslationUnit().getCProject() : null;
CFormatter formatter= new CFormatter(TextUtilities.getDefaultLineDelimiter(getDocument()), getIndentationLevel(project), useCodeFormatter, project);
formatter.format(buffer, this);
return buffer;
}
/**
* Returns the indentation level at the position of code completion.
*/
private int getIndentation() {
private int getIndentationLevel(ICProject project) {
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());
return Strings.computeIndent(lineContent, CodeFormatterUtil.getTabWidth(project), CodeFormatterUtil.getIndentWidth(project));
} catch (BadLocationException e) {
return 0;
}
}
}

View file

@ -9,35 +9,44 @@
* IBM Corporation - initial API and implementation
* Qnx Software System
* Anton Leherbauer (Wind River Systems) - Fixed bug 126617
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.corext.template.c;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.formatter.CodeFormatter;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.internal.corext.util.CodeFormatterUtil;
import org.eclipse.cdt.internal.ui.editor.CEditor;
import org.eclipse.cdt.internal.ui.util.Strings;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.cdt.internal.ui.editor.IndentUtil;
import org.eclipse.cdt.internal.ui.text.FastCPartitionScanner;
import org.eclipse.cdt.ui.text.ICPartitions;
import org.eclipse.jface.text.Assert;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.BadPositionCategoryException;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.TypedPosition;
import org.eclipse.jface.text.rules.FastPartitioner;
import org.eclipse.jface.text.source.LineRange;
import org.eclipse.jface.text.templates.DocumentTemplateContext;
import org.eclipse.jface.text.templates.TemplateBuffer;
import org.eclipse.jface.text.templates.TemplateContext;
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;
import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants;
/**
@ -45,6 +54,8 @@ import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants;
*/
public class CFormatter {
private static final String COMMENT_START= "/*-"; //$NON-NLS-1$
private static final String COMMENT_END= "*/"; //$NON-NLS-1$
// private static final String CURSOR= "cursor"; //$NON-NLS-1$
// private static final String MARKER= "/*${cursor}*/"; //$NON-NLS-1$
@ -55,40 +66,101 @@ public class CFormatter {
/** Flag indicating whether to use the code formatter or not. */
private boolean fUseCodeFormatter;
private final ICProject fProject;
public CFormatter(String lineDelimiter, int initialIndentLevel, boolean useCodeFormatter) {
/**
* Creates a CFormatter with the target line delimiter.
*
* @param lineDelimiter the line delimiter to use
* @param initialIndentLevel the initial indentation level
* @param useCodeFormatter <code>true</code> if the core code formatter should be used
* @param project the C/C++ project from which to get the preferences, or <code>null</code> for workbench settings
*/
public CFormatter(String lineDelimiter, int initialIndentLevel, boolean useCodeFormatter, ICProject project) {
fLineDelimiter= lineDelimiter;
fUseCodeFormatter= useCodeFormatter;
fInitialIndentLevel= initialIndentLevel;
fProject= project;
}
public void edit(TemplateBuffer buffer, CContext context, int indentationLevel) throws BadLocationException {
/**
* Formats the template buffer.
* @param buffer
* @param context
* @throws BadLocationException
*/
public void format(TemplateBuffer buffer, TemplateContext context) 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);
}
VariableTracker tracker= new VariableTracker(buffer);
IDocument document= tracker.getDocument();
// 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;
internalFormat(document, context);
convertLineDelimiters(document);
if (!isReplacedAreaEmpty(context))
trimStart(document);
trimBegin(buffer);
tracker.updateBuffer();
} catch (MalformedTreeException e) {
throw new BadLocationException();
}
}
/**
* @param document
* @param context
* @throws BadLocationException
*/
private void internalFormat(IDocument document, TemplateContext context) throws BadLocationException {
if (fUseCodeFormatter) {
// try to format and fall back to indenting
try {
format(document, (TranslationUnitContext) context);
} catch (BadLocationException e) {
indent(document);
} catch (MalformedTreeException e) {
indent(document);
}
} else {
indent(document);
}
}
private void convertLineDelimiters(IDocument document) throws BadLocationException {
int lines= document.getNumberOfLines();
for (int line= 0; line < lines; line++) {
IRegion region= document.getLineInformation(line);
String lineDelimiter= document.getLineDelimiter(line);
if (lineDelimiter != null)
document.replace(region.getOffset() + region.getLength(), lineDelimiter.length(), fLineDelimiter);
}
}
private void trimStart(IDocument document) throws BadLocationException {
int i= 0;
while ((i != document.getLength()) && Character.isWhitespace(document.getChar(i)))
i++;
document.replace(0, i, ""); //$NON-NLS-1$
}
private boolean isReplacedAreaEmpty(TemplateContext context) {
// don't trim the buffer if the replacement area is empty
// case: surrounding empty lines with block
if (context instanceof DocumentTemplateContext) {
DocumentTemplateContext dtc= (DocumentTemplateContext) context;
if (dtc.getStart() == dtc.getCompletionOffset())
try {
if (dtc.getDocument().get(dtc.getStart(), dtc.getEnd() - dtc.getStart()).trim().length() == 0)
return true;
} catch (BadLocationException x) {
// ignore - this may happen when the document was modified after the initial invocation, and the
// context does not track the changes properly - don't trim in that case
return true;
}
}
return false;
}
// private static int getCaretOffset(TemplateVariable[] variables) {
// for (int i= 0; i != variables.length; i++) {
// TemplateVariable variable= variables[i];
@ -119,52 +191,7 @@ public class CFormatter {
// }
// }
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);
}
private void plainFormat(TemplateBuffer templateBuffer, CContext context) throws BadLocationException {
IDocument doc= new Document(templateBuffer.getString());
TemplateVariable[] variables= templateBuffer.getVariables();
List offsets= variablesToPositions(variables);
private void format(IDocument doc, TranslationUnitContext context) throws BadLocationException {
Map options;
if (context.getTranslationUnit() != null)
options= context.getTranslationUnit().getCProject().getOptions(true);
@ -175,209 +202,184 @@ public class CFormatter {
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
}
edit.apply(doc, TextEdit.UPDATE_REGIONS);
}
root.apply(doc, TextEdit.UPDATE_REGIONS);
positionsToVariables(offsets, variables);
templateBuffer.setContent(doc.get(), variables);
}
private void indent(TemplateBuffer templateBuffer) throws BadLocationException, MalformedTreeException {
TemplateVariable[] variables= templateBuffer.getVariables();
List positions= variablesToPositions(variables);
IDocument document= new Document(templateBuffer.getString());
MultiTextEdit root= new MultiTextEdit(0, document.getLength());
root.addChildren((TextEdit[]) positions.toArray(new TextEdit[positions.size()]));
IPreferenceStore store = CUIPlugin.getDefault().getCombinedPreferenceStore();
boolean useSpaces = store.getBoolean(CEditor.SPACES_FOR_TABS);
int tabWidth = store
.getInt(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH);
int indentWidth = tabWidth;
String indent = createIndentString(fInitialIndentLevel * indentWidth, tabWidth, useSpaces);
private void indent(IDocument document) throws BadLocationException, MalformedTreeException {
// 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);
document.replace(offset, 0, CodeFormatterUtil.createIndentString(fInitialIndentLevel, fProject));
// following lines
int lineCount= document.getNumberOfLines();
for (int line= 1; line < lineCount; line++) {
IRegion region= document.getLineInformation(line);
String lineContent= document.get(region.getOffset(), region.getLength());
String lineIndent= Strings.getIndentString(lineContent, tabWidth);
int lineIndentLevel= Strings.computeIndent(lineIndent, tabWidth);
indent= createIndentString((fInitialIndentLevel + lineIndentLevel) * indentWidth, tabWidth, useSpaces);
edit= new ReplaceEdit(region.getOffset(), lineIndent.length(), indent);
root.addChild(edit);
root.apply(document, TextEdit.UPDATE_REGIONS);
root.removeChild(edit);
formatDelimiter(document, root, line);
}
positionsToVariables(positions, variables);
templateBuffer.setContent(document.get(), variables);
IndentUtil.indentLines(document, new LineRange(1, lineCount - 1), fProject, null);
}
/**
* Changes the delimiter to the configured line delimiter.
*
* @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
* Wraps a {@link TemplateBuffer} and tracks the variable offsets while changes to the buffer
* occur. Whitespace variables are also tracked.
*/
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);
}
}
private static final class VariableTracker {
private static final String CATEGORY= "__template_variables"; //$NON-NLS-1$
private Document fDocument;
private final TemplateBuffer fBuffer;
private List fPositions;
private static void trimBegin(TemplateBuffer templateBuffer) throws BadLocationException {
String string= templateBuffer.getString();
TemplateVariable[] variables= templateBuffer.getVariables();
List positions= variablesToPositions(variables);
int i= 0;
while ((i != string.length()) && Character.isWhitespace(string.charAt(i)))
i++;
string= edit(string, positions, new DeleteEdit(0, i));
positionsToVariables(positions, variables);
templateBuffer.setContent(string, variables);
}
private static String edit(String string, List positions, TextEdit edit) throws BadLocationException {
MultiTextEdit root= new MultiTextEdit(0, string.length());
root.addChildren((TextEdit[]) positions.toArray(new TextEdit[positions.size()]));
root.addChild(edit);
IDocument document= new Document(string);
root.apply(document);
return document.get();
/**
* Creates a new tracker.
*
* @param buffer the buffer to track
* @throws MalformedTreeException
* @throws BadLocationException
*/
public VariableTracker(TemplateBuffer buffer) throws MalformedTreeException, BadLocationException {
Assert.isLegal(buffer != null);
fBuffer= buffer;
fDocument= new Document(fBuffer.getString());
installCStuff(fDocument);
fDocument.addPositionCategory(CATEGORY);
fDocument.addPositionUpdater(new ExclusivePositionUpdater(CATEGORY));
fPositions= createRangeMarkers(fBuffer.getVariables(), fDocument);
}
/**
* Create an indent string suitable as line prefix using the given
* formatting options.
* Installs a C partitioner with <code>document</code>.
*
* @param displayedWidth
* the desired displayed width (in char units)
* @param tabWidth
* the displayed tab width
* @param useSpaces
* if <code>true</code>, only spaces are used for the indent
* string, otherwise, the indent string will contain mixed tabs
* and spaces.
* @return the new indent string
* @param document the document
*/
private static String createIndentString(int displayedWidth,
int tabWidth, boolean useSpaces) {
return appendIndentString(new StringBuffer(displayedWidth),
displayedWidth, tabWidth, useSpaces, 0).toString();
private static void installCStuff(Document document) {
String[] types= new String[] {
ICPartitions.C_MULTI_LINE_COMMENT,
ICPartitions.C_SINGLE_LINE_COMMENT,
ICPartitions.C_STRING,
ICPartitions.C_CHARACTER,
IDocument.DEFAULT_CONTENT_TYPE
};
FastPartitioner partitioner= new FastPartitioner(new FastCPartitionScanner(), types);
partitioner.connect(document);
document.setDocumentPartitioner(ICPartitions.C_PARTITIONING, partitioner);
}
/**
* Append an indent string to the given buffer so that the resulting string
* ends at the desired column.
* Returns the document with the buffer contents. Whitespace variables are decorated with
* comments.
*
* @param buffer
* the StringBuffer to append to
* @param displayedWidth
* the desired displayed width (in char units)
* @param tabWidth
* the displayed tab width
* @param useSpaces
* if <code>true</code>, only spaces are used for the indent
* string, otherwise, the indent string will contain mixed tabs
* and spaces.
* @param startColumn
* the displayed starting column to correctly identify the tab
* stops
* @return the same StringBuffer as provided
* @return the buffer document
*/
private static StringBuffer appendIndentString(StringBuffer buffer,
int displayedWidth, int tabWidth, boolean useSpaces, int startColumn) {
int tabStop= startColumn - startColumn % tabWidth;
int tabs= useSpaces ? 0 : (displayedWidth - tabStop) / tabWidth;
for (int i= 0; i < tabs; ++i) {
buffer.append('\t');
tabStop += tabWidth;
startColumn= tabStop;
}
int spaces= displayedWidth - startColumn;
for (int i= 0; i < spaces; ++i) {
buffer.append(' ');
}
return buffer;
public IDocument getDocument() {
checkState();
return fDocument;
}
private static List variablesToPositions(TemplateVariable[] variables) {
List positions= new ArrayList(5);
private void checkState() {
if (fDocument == null)
throw new IllegalStateException();
}
/**
* Restores any decorated regions and updates the buffer's variable offsets.
*
* @return the buffer.
* @throws MalformedTreeException
* @throws BadLocationException
*/
public TemplateBuffer updateBuffer() throws MalformedTreeException, BadLocationException {
checkState();
TemplateVariable[] variables= fBuffer.getVariables();
try {
removeRangeMarkers(fPositions, fDocument, variables);
} catch (BadPositionCategoryException x) {
Assert.isTrue(false);
}
fBuffer.setContent(fDocument.get(), variables);
fDocument= null;
return fBuffer;
}
private List createRangeMarkers(TemplateVariable[] variables, IDocument document) throws MalformedTreeException, BadLocationException {
Map markerToOriginal= new HashMap();
MultiTextEdit root= new MultiTextEdit(0, document.getLength());
List edits= new ArrayList();
boolean hasModifications= false;
for (int i= 0; i != variables.length; i++) {
int[] offsets= variables[i].getOffsets();
// trim positions off whitespace
String value= variables[i].getDefaultValue();
int wsStart= 0;
while (wsStart < value.length() && Character.isWhitespace(value.charAt(wsStart)) && !Strings.isLineDelimiterChar(value.charAt(wsStart)))
wsStart++;
variables[i].getValues()[0]= value.substring(wsStart);
final TemplateVariable variable= variables[i];
int[] offsets= variable.getOffsets();
String value= variable.getDefaultValue();
if (isWhitespaceVariable(value)) {
// replace whitespace positions with unformattable comments
String placeholder= COMMENT_START + value + COMMENT_END;
for (int j= 0; j != offsets.length; j++) {
offsets[j] += wsStart;
positions.add(new RangeMarker(offsets[j], 0));
ReplaceEdit replace= new ReplaceEdit(offsets[j], value.length(), placeholder);
root.addChild(replace);
hasModifications= true;
markerToOriginal.put(replace, value);
edits.add(replace);
}
} else {
for (int j= 0; j != offsets.length; j++) {
RangeMarker marker= new RangeMarker(offsets[j], value.length());
root.addChild(marker);
edits.add(marker);
}
}
}
if (hasModifications) {
// update the document and convert the replaces to markers
root.apply(document, TextEdit.UPDATE_REGIONS);
}
List positions= new ArrayList();
for (Iterator it= edits.iterator(); it.hasNext();) {
TextEdit edit= (TextEdit) it.next();
try {
// abuse TypedPosition to piggy back the original contents of the position
final TypedPosition pos= new TypedPosition(edit.getOffset(), edit.getLength(), (String) markerToOriginal.get(edit));
document.addPosition(CATEGORY, pos);
positions.add(pos);
} catch (BadPositionCategoryException x) {
Assert.isTrue(false);
}
}
return positions;
}
private static void positionsToVariables(List positions, TemplateVariable[] variables) {
Iterator iterator= positions.iterator();
private boolean isWhitespaceVariable(String value) {
int length= value.length();
return length == 0 || Character.isWhitespace(value.charAt(0)) || Character.isWhitespace(value.charAt(length - 1));
}
private void removeRangeMarkers(List positions, IDocument document, TemplateVariable[] variables) throws MalformedTreeException, BadLocationException, BadPositionCategoryException {
// revert previous changes
for (Iterator it= positions.iterator(); it.hasNext();) {
TypedPosition position= (TypedPosition) it.next();
// remove and re-add in order to not confuse ExclusivePositionUpdater
document.removePosition(CATEGORY, position);
final String original= position.getType();
if (original != null) {
document.replace(position.getOffset(), position.getLength(), original);
position.setLength(original.length());
}
document.addPosition(position);
}
Iterator it= positions.iterator();
for (int i= 0; i != variables.length; i++) {
TemplateVariable variable= variables[i];
int[] offsets= new int[variable.getOffsets().length];
for (int j= 0; j != offsets.length; j++)
offsets[j]= ((TextEdit) iterator.next()).getOffset();
offsets[j]= ((Position) it.next()).getOffset();
variable.setOffsets(offsets);
}
}
}
}
}

View file

@ -0,0 +1,99 @@
/*******************************************************************************
* Copyright (c) 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.corext.template.c;
import org.eclipse.jface.text.BadPositionCategoryException;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IPositionUpdater;
import org.eclipse.jface.text.Position;
/**
* Position updater that takes any changes at the borders of a position to not belong to the position.
*/
final class ExclusivePositionUpdater implements IPositionUpdater {
/** The position category. */
private final String fCategory;
/**
* Creates a new updater for the given <code>category</code>.
*
* @param category the new category.
*/
public ExclusivePositionUpdater(String category) {
fCategory= category;
}
/*
* @see org.eclipse.jface.text.IPositionUpdater#update(org.eclipse.jface.text.DocumentEvent)
*/
public void update(DocumentEvent event) {
int eventOffset= event.getOffset();
int eventOldLength= event.getLength();
int eventNewLength= event.getText() == null ? 0 : event.getText().length();
int deltaLength= eventNewLength - eventOldLength;
try {
Position[] positions= event.getDocument().getPositions(fCategory);
for (int i= 0; i != positions.length; i++) {
Position position= positions[i];
if (position.isDeleted())
continue;
int offset= position.getOffset();
int length= position.getLength();
int end= offset + length;
if (offset >= eventOffset + eventOldLength)
// position comes
// after change - shift
position.setOffset(offset + deltaLength);
else if (end <= eventOffset) {
// position comes way before change -
// leave alone
} else if (offset <= eventOffset && end >= eventOffset + eventOldLength) {
// event completely internal to the position - adjust length
position.setLength(length + deltaLength);
} else if (offset < eventOffset) {
// event extends over end of position - adjust length
int newEnd= eventOffset;
position.setLength(newEnd - offset);
} else if (end > eventOffset + eventOldLength) {
// event extends from before position into it - adjust offset
// and length
// offset becomes end of event, length adjusted accordingly
int newOffset= eventOffset + eventNewLength;
position.setOffset(newOffset);
position.setLength(end - newOffset);
} else {
// event consumes the position - delete it
position.delete();
}
}
} catch (BadPositionCategoryException e) {
// ignore and return
}
}
/**
* Returns the position category.
*
* @return the position category
*/
public String getCategory() {
return fCategory;
}
}

View file

@ -15,29 +15,34 @@ import java.util.Map;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.ToolFactory;
import org.eclipse.cdt.core.formatter.CodeFormatter;
import org.eclipse.cdt.core.formatter.CodeFormatterConstants;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.core.runtime.Assert;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.BadPositionCategoryException;
import org.eclipse.jface.text.DefaultPositionUpdater;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.Position;
import org.eclipse.text.edits.TextEdit;
import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants;
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'));
// }
/**
* Creates a string that represents the given number of indentation units.
* The returned string can contain tabs and/or spaces depending on the core
* formatter preferences.
*
* @param indentationUnits the number of indentation units to generate
* @param project the project from which to get the formatter settings,
* <code>null</code> if the workspace default should be used
* @return the indent string
*/
public static String createIndentString(int indentationUnits, ICProject project) {
Map options= project != null ? project.getOptions(true) : CCorePlugin.getOptions();
return ToolFactory.createDefaultCodeFormatter(options).createIndentationString(indentationUnits);
}
/**
* Gets the current tab width.
@ -55,10 +60,10 @@ public class CodeFormatterUtil {
* that case.
*/
String key;
if (CCorePlugin.SPACE.equals(getCoreOption(project, CodeFormatterConstants.FORMATTER_TAB_CHAR)))
key= CodeFormatterConstants.FORMATTER_INDENTATION_SIZE;
if (CCorePlugin.SPACE.equals(getCoreOption(project, DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR)))
key= DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE;
else
key= CodeFormatterConstants.FORMATTER_TAB_SIZE;
key= DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE;
return getCoreOption(project, key, 4);
}
@ -72,10 +77,10 @@ public class CodeFormatterUtil {
*/
public static int getIndentWidth(ICProject project) {
String key;
if (CodeFormatterConstants.MIXED.equals(getCoreOption(project, CodeFormatterConstants.FORMATTER_TAB_CHAR)))
key= CodeFormatterConstants.FORMATTER_INDENTATION_SIZE;
if (DefaultCodeFormatterConstants.MIXED.equals(getCoreOption(project, DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR)))
key= DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE;
else
key= CodeFormatterConstants.FORMATTER_TAB_SIZE;
key= DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE;
return getCoreOption(project, key, 4);
}
@ -131,7 +136,7 @@ public class CodeFormatterUtil {
return doc.get();
} catch (BadLocationException e) {
CUIPlugin.getDefault().log(e); // bug in the formatter
Assert.isTrue(false, "Fromatter created edits with wrong positions: " + e.getMessage()); //$NON-NLS-1$
Assert.isTrue(false, "Formatter created edits with wrong positions: " + e.getMessage()); //$NON-NLS-1$
}
return null;
}
@ -213,9 +218,10 @@ public class CodeFormatterUtil {
return doc;
}
/**
* @return The formatter tab width on workspace level.
*/
public static int getTabWidth() {
IPreferenceStore store = CUIPlugin.getDefault().getCombinedPreferenceStore();
return store.getInt(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH);
return getTabWidth(null);
}
}

View file

@ -53,6 +53,7 @@ public interface ICHelpContextIds {
public static final String C_EDITOR_CONTENT_ASSIST_PREF_PAGE = PREFIX + "c_editor_con_assist"; //$NON-NLS-1$
public static final String C_EDITOR_NAVIGATION_PAGE = PREFIX + "c_editor_navigation"; //$NON-NLS-1$
public static final String C_EDITOR_HOVERS_PAGE = PREFIX + "c_editor_hov"; //$NON-NLS-1$
public static final String C_EDITOR_TYPING_PAGE = PREFIX + "c_editor_typing"; //$NON-NLS-1$;
public static final String FILE_TYPES_STD_PAGE = PREFIX + "std_prop_file_types"; //$NON-NLS-1$
public static final String FILE_TYPES_MAN_PAGE = PREFIX + "std_prop_file_types"; //$NON-NLS-1$
public static final String FILE_TYPES_PREF_PAGE = PREFIX + "c_file_types"; //$NON-NLS-1$

View file

@ -0,0 +1,573 @@
/*******************************************************************************
* Copyright (c) 2000, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.ui.actions;
import java.util.ResourceBundle;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.widgets.Display;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.text.Assert;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.IRewriteTarget;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.ui.texteditor.ITextEditorExtension3;
import org.eclipse.ui.texteditor.TextEditorAction;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.ui.text.ICPartitions;
import org.eclipse.cdt.internal.ui.editor.CEditor;
import org.eclipse.cdt.internal.ui.text.CHeuristicScanner;
import org.eclipse.cdt.internal.ui.text.CIndenter;
/**
* Indents a line or range of lines in a C document to its correct position. No complete
* AST must be present, the indentation is computed using heuristics. The algorithm used is fast for
* single lines, but does not store any information and therefore not so efficient for large line
* ranges.
*
* @see org.eclipse.cdt.internal.ui.text.CHeuristicScanner
* @see org.eclipse.cdt.internal.ui.text.CIndenter
*/
public class IndentAction extends TextEditorAction {
/** The caret offset after an indent operation. */
private int fCaretOffset;
/**
* Whether this is the action invoked by TAB. When <code>true</code>, indentation behaves
* differently to accommodate normal TAB operation.
*/
private final boolean fIsTabAction;
/**
* Creates a new instance.
*
* @param bundle the resource bundle
* @param prefix the prefix to use for keys in <code>bundle</code>
* @param editor the text editor
* @param isTabAction whether the action should insert tabs if over the indentation
*/
public IndentAction(ResourceBundle bundle, String prefix, ITextEditor editor, boolean isTabAction) {
super(bundle, prefix, editor);
fIsTabAction= isTabAction;
}
/*
* @see org.eclipse.jface.action.Action#run()
*/
public void run() {
// update has been called by the framework
if (!isEnabled() || !validateEditorInputState())
return;
ITextSelection selection= getSelection();
final IDocument document= getDocument();
if (document != null) {
final int offset= selection.getOffset();
final int length= selection.getLength();
final Position end= new Position(offset + length);
final int firstLine, nLines;
fCaretOffset= -1;
try {
document.addPosition(end);
firstLine= document.getLineOfOffset(offset);
// check for marginal (zero-length) lines
int minusOne= length == 0 ? 0 : 1;
nLines= document.getLineOfOffset(offset + length - minusOne) - firstLine + 1;
} catch (BadLocationException e) {
// will only happen on concurrent modification
CUIPlugin.getDefault().log(new Status(IStatus.ERROR, CUIPlugin.getPluginId(), IStatus.OK, "", e)); //$NON-NLS-1$
return;
}
Runnable runnable= new Runnable() {
public void run() {
IRewriteTarget target= (IRewriteTarget)getTextEditor().getAdapter(IRewriteTarget.class);
if (target != null)
target.beginCompoundChange();
try {
CHeuristicScanner scanner= new CHeuristicScanner(document);
CIndenter indenter= new CIndenter(document, scanner, getCProject());
final boolean multiLine= nLines > 1;
boolean hasChanged= false;
for (int i= 0; i < nLines; i++) {
hasChanged |= indentLine(document, firstLine + i, offset, indenter, scanner, multiLine);
}
// update caret position: move to new position when indenting just one line
// keep selection when indenting multiple
int newOffset, newLength;
if (!fIsTabAction && multiLine) {
newOffset= offset;
newLength= end.getOffset() - offset;
} else {
newOffset= fCaretOffset;
newLength= 0;
}
// always reset the selection if anything was replaced
// but not when we had a single line non-tab invocation
if (newOffset != -1 && (hasChanged || newOffset != offset || newLength != length))
selectAndReveal(newOffset, newLength);
document.removePosition(end);
} catch (BadLocationException e) {
// will only happen on concurrent modification
CUIPlugin.getDefault().log(new Status(IStatus.ERROR, CUIPlugin.getPluginId(), IStatus.OK, "ConcurrentModification in IndentAction", e)); //$NON-NLS-1$
} finally {
if (target != null)
target.endCompoundChange();
}
}
};
if (nLines > 50) {
Display display= getTextEditor().getEditorSite().getWorkbenchWindow().getShell().getDisplay();
BusyIndicator.showWhile(display, runnable);
} else {
runnable.run();
}
}
}
/**
* Selects the given range on the editor.
*
* @param newOffset the selection offset
* @param newLength the selection range
*/
private void selectAndReveal(int newOffset, int newLength) {
Assert.isTrue(newOffset >= 0);
Assert.isTrue(newLength >= 0);
ITextEditor editor= getTextEditor();
if (editor instanceof CEditor) {
ISourceViewer viewer= ((CEditor)editor).getViewer();
if (viewer != null)
viewer.setSelectedRange(newOffset, newLength);
} else {
// this is too intrusive, but will never get called anyway
getTextEditor().selectAndReveal(newOffset, newLength);
}
}
/**
* Indents a single line using the java heuristic scanner. Cdoc and multiline comments are
* indented as specified by the <code>CDocAutoIndentStrategy</code>.
*
* @param document the document
* @param line the line to be indented
* @param caret the caret position
* @param indenter the java indenter
* @param scanner the heuristic scanner
* @param multiLine <code>true</code> if more than one line is being indented
* @return <code>true</code> if <code>document</code> was modified, <code>false</code> otherwise
* @throws BadLocationException if the document got changed concurrently
*/
private boolean indentLine(IDocument document, int line, int caret, CIndenter indenter, CHeuristicScanner scanner, boolean multiLine) throws BadLocationException {
IRegion currentLine= document.getLineInformation(line);
int offset= currentLine.getOffset();
int wsStart= offset; // where we start searching for non-WS; after the "//" in single line comments
String indent= null;
if (offset < document.getLength()) {
ITypedRegion partition= TextUtilities.getPartition(document, ICPartitions.C_PARTITIONING, offset, true);
ITypedRegion startingPartition= TextUtilities.getPartition(document, ICPartitions.C_PARTITIONING, offset, false);
String type= partition.getType();
if (type.equals(ICPartitions.C_MULTI_LINE_COMMENT)) {
indent= computeDocIndent(document, line, scanner, startingPartition);
} else if (!fIsTabAction && startingPartition.getOffset() == offset && startingPartition.getType().equals(ICPartitions.C_SINGLE_LINE_COMMENT)) {
// line comment starting at position 0 -> indent inside
int max= document.getLength() - offset;
int slashes= 2;
while (slashes < max - 1 && document.get(offset + slashes, 2).equals("//")) //$NON-NLS-1$
slashes+= 2;
wsStart= offset + slashes;
StringBuffer computed= indenter.computeIndentation(offset);
if (computed == null)
computed= new StringBuffer(0);
int tabSize= getTabSize();
while (slashes > 0 && computed.length() > 0) {
char c= computed.charAt(0);
if (c == '\t') {
if (slashes > tabSize)
slashes-= tabSize;
else
break;
} else if (c == ' ') {
slashes--;
} else {
break;
}
computed.deleteCharAt(0);
}
indent= document.get(offset, wsStart - offset) + computed;
}
}
// standard java indentation
if (indent == null) {
StringBuffer computed= indenter.computeIndentation(offset);
if (computed != null)
indent= computed.toString();
else
indent= ""; //$NON-NLS-1$
}
// change document:
// get current white space
int lineLength= currentLine.getLength();
int end= scanner.findNonWhitespaceForwardInAnyPartition(wsStart, offset + lineLength);
if (end == CHeuristicScanner.NOT_FOUND) {
// an empty line
end= offset + lineLength;
if (multiLine && !indentEmptyLines())
indent= ""; //$NON-NLS-1$
}
int length= end - offset;
String currentIndent= document.get(offset, length);
// if we are right before the text start / line end, and already after the insertion point
// then just insert a tab.
if (fIsTabAction && caret == end && whiteSpaceLength(currentIndent) >= whiteSpaceLength(indent)) {
String tab= getTabEquivalent();
document.replace(caret, 0, tab);
fCaretOffset= caret + tab.length();
return true;
}
// set the caret offset so it can be used when setting the selection
if (caret >= offset && caret <= end)
fCaretOffset= offset + indent.length();
else
fCaretOffset= -1;
// only change the document if it is a real change
if (!indent.equals(currentIndent)) {
document.replace(offset, length, indent);
return true;
} else {
return false;
}
}
/**
* Computes and returns the indentation for a javadoc line. The line
* must be inside a javadoc comment.
*
* @param document the document
* @param line the line in document
* @param scanner the scanner
* @param partition the javadoc partition
* @return the indent, or <code>null</code> if not computable
* @throws BadLocationException
*/
private String computeDocIndent(IDocument document, int line, CHeuristicScanner scanner, ITypedRegion partition) throws BadLocationException {
if (line == 0) // impossible - the first line is never inside a javadoc comment
return null;
// don't make any assumptions if the line does not start with \s*\* - it might be
// commented out code, for which we don't want to change the indent
final IRegion lineInfo= document.getLineInformation(line);
final int lineStart= lineInfo.getOffset();
final int lineLength= lineInfo.getLength();
final int lineEnd= lineStart + lineLength;
int nonWS= scanner.findNonWhitespaceForwardInAnyPartition(lineStart, lineEnd);
if (nonWS == CHeuristicScanner.NOT_FOUND || document.getChar(nonWS) != '*') {
if (nonWS == CHeuristicScanner.NOT_FOUND)
return document.get(lineStart, lineLength);
return document.get(lineStart, nonWS - lineStart);
}
// take the indent from the previous line and reuse
IRegion previousLine= document.getLineInformation(line - 1);
int previousLineStart= previousLine.getOffset();
int previousLineLength= previousLine.getLength();
int previousLineEnd= previousLineStart + previousLineLength;
StringBuffer buf= new StringBuffer();
int previousLineNonWS= scanner.findNonWhitespaceForwardInAnyPartition(previousLineStart, previousLineEnd);
if (previousLineNonWS == CHeuristicScanner.NOT_FOUND || document.getChar(previousLineNonWS) != '*') {
// align with the comment start if the previous line is not an asterisked line
previousLine= document.getLineInformationOfOffset(partition.getOffset());
previousLineStart= previousLine.getOffset();
previousLineLength= previousLine.getLength();
previousLineEnd= previousLineStart + previousLineLength;
previousLineNonWS= scanner.findNonWhitespaceForwardInAnyPartition(previousLineStart, previousLineEnd);
if (previousLineNonWS == CHeuristicScanner.NOT_FOUND)
previousLineNonWS= previousLineEnd;
// add the initial space
// TODO this may be controlled by a formatter preference in the future
buf.append(' ');
}
String indentation= document.get(previousLineStart, previousLineNonWS - previousLineStart);
buf.insert(0, indentation);
return buf.toString();
}
/**
* Returns the size in characters of a string. All characters count one, tabs count the editor's
* preference for the tab display
*
* @param indent the string to be measured.
* @return the size in characters of a string
*/
private int whiteSpaceLength(String indent) {
if (indent == null)
return 0;
else {
int size= 0;
int l= indent.length();
int tabSize= getTabSize();
for (int i= 0; i < l; i++)
size += indent.charAt(i) == '\t' ? tabSize : 1;
return size;
}
}
/**
* Returns a tab equivalent, either as a tab character or as spaces, depending on the editor and
* formatter preferences.
*
* @return a string representing one tab in the editor, never <code>null</code>
*/
private String getTabEquivalent() {
String tab;
if (CCorePlugin.SPACE.equals(getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR))) {
int size= getTabSize();
StringBuffer buf= new StringBuffer();
for (int i= 0; i< size; i++)
buf.append(' ');
tab= buf.toString();
} else {
tab= "\t"; //$NON-NLS-1$
}
return tab;
}
/**
* Returns the tab size used by the java editor, which is deduced from the
* formatter preferences.
*
* @return the tab size as defined in the current formatter preferences
*/
private int getTabSize() {
return getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, 4);
}
/**
* Returns <code>true</code> if empty lines should be indented, false otherwise.
*
* @return <code>true</code> if empty lines should be indented, false otherwise
*/
private boolean indentEmptyLines() {
return DefaultCodeFormatterConstants.TRUE.equals(getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_INDENT_EMPTY_LINES));
}
/**
* Returns the possibly project-specific core preference defined under <code>key</code>.
*
* @param key the key of the preference
* @return the value of the preference
*/
private String getCoreFormatterOption(String key) {
ICProject project= getCProject();
if (project == null)
return CCorePlugin.getOption(key);
return project.getOption(key, true);
}
/**
* Returns the possibly project-specific core preference defined under <code>key</code>, or
* <code>def</code> if the value is not a integer.
*
* @param key the key of the preference
* @param def the default value
* @return the value of the preference
*/
private int getCoreFormatterOption(String key, int def) {
try {
return Integer.parseInt(getCoreFormatterOption(key));
} catch (NumberFormatException e) {
return def;
}
}
/**
* Returns the <code>ICProject</code> of the current editor input, or
* <code>null</code> if it cannot be found.
*
* @return the <code>ICProject</code> of the current editor input, or
* <code>null</code> if it cannot be found
*/
private ICProject getCProject() {
ITextEditor editor= getTextEditor();
if (editor == null)
return null;
ITranslationUnit cu= CUIPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(editor.getEditorInput());
if (cu == null)
return null;
return cu.getCProject();
}
/**
* Returns the editor's selection provider.
*
* @return the editor's selection provider or <code>null</code>
*/
private ISelectionProvider getSelectionProvider() {
ITextEditor editor= getTextEditor();
if (editor != null) {
return editor.getSelectionProvider();
}
return null;
}
/*
* @see org.eclipse.ui.texteditor.IUpdate#update()
*/
public void update() {
super.update();
if (isEnabled()) {
if (fIsTabAction)
setEnabled(canModifyEditor() && isSmartMode() && isValidSelection());
else
setEnabled(canModifyEditor() && !getSelection().isEmpty());
}
}
/**
* Returns if the current selection is valid, i.e. whether it is empty and the caret in the
* whitespace at the start of a line, or covers multiple lines.
*
* @return <code>true</code> if the selection is valid for an indent operation
*/
private boolean isValidSelection() {
ITextSelection selection= getSelection();
if (selection.isEmpty())
return false;
int offset= selection.getOffset();
int length= selection.getLength();
IDocument document= getDocument();
if (document == null)
return false;
try {
IRegion firstLine= document.getLineInformationOfOffset(offset);
int lineOffset= firstLine.getOffset();
// either the selection has to be empty and the caret in the WS at the line start
// or the selection has to extend over multiple lines
if (length == 0) {
return document.get(lineOffset, offset - lineOffset).trim().length() == 0;
} else {
// return lineOffset + firstLine.getLength() < offset + length;
return false; // only enable for empty selections for now
}
} catch (BadLocationException e) {
}
return false;
}
/**
* Returns the smart preference state.
*
* @return <code>true</code> if smart mode is on, <code>false</code> otherwise
*/
private boolean isSmartMode() {
ITextEditor editor= getTextEditor();
if (editor instanceof ITextEditorExtension3)
return ((ITextEditorExtension3) editor).getInsertMode() == ITextEditorExtension3.SMART_INSERT;
return false;
}
/**
* Returns the document currently displayed in the editor, or <code>null</code> if none can be
* obtained.
*
* @return the current document or <code>null</code>
*/
private IDocument getDocument() {
ITextEditor editor= getTextEditor();
if (editor != null) {
IDocumentProvider provider= editor.getDocumentProvider();
IEditorInput input= editor.getEditorInput();
if (provider != null && input != null)
return provider.getDocument(input);
}
return null;
}
/**
* Returns the selection on the editor or an invalid selection if none can be obtained. Returns
* never <code>null</code>.
*
* @return the current selection, never <code>null</code>
*/
private ITextSelection getSelection() {
ISelectionProvider provider= getSelectionProvider();
if (provider != null) {
ISelection selection= provider.getSelection();
if (selection instanceof ITextSelection)
return (ITextSelection) selection;
}
// null object
return TextSelection.emptySelection();
}
}

View file

@ -97,6 +97,10 @@ PreviousAnnotation.label= Pre&vious Annotation
PreviousAnnotation.tooltip= Previous Annotation
PreviousAnnotation.description= Previous Annotation
Indent.label=Correct &Indentation
Indent.tooltip=&Indent Current Line to Correct Indentation
Indent.description=&Indents the current line or selection depending on surrounding source code
AddIncludeOnSelectionAction.error.noInput=no Editor Input
DefaultCEditorTextHover.html.name=<b>Name:</b>
DefaultCEditorTextHover.html.prototype=<br><b>Protoype:</b>

View file

@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2005 QNX Software Systems and others.
* Copyright (c) 2006 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@ -7,6 +7,7 @@
*
* Contributors:
* QNX Software Systems - initial API and implementation
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.ui.editor;
@ -14,10 +15,6 @@ import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.content.IContentType;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.text.Assert;
@ -40,20 +37,9 @@ import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IPathEditorInput;
import org.eclipse.ui.editors.text.ILocationProvider;
import org.eclipse.ui.ide.ResourceUtil;
import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants;
import org.eclipse.ui.texteditor.AbstractTextEditor;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ILanguage;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.core.model.LanguageManager;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.ui.editor.CEditor.ITextConverter;
import org.eclipse.cdt.internal.ui.text.CSourceViewerConfiguration;
@ -66,7 +52,7 @@ public class CSourceViewer extends ProjectionViewer implements IPropertyChangeLi
public static final int SHOW_OUTLINE = 101;
/** Editor. */
private final CEditor editor;
private CEditor editor;
/** Presents outline. */
private IInformationPresenter fOutlinePresenter;
@ -107,21 +93,15 @@ public class CSourceViewer extends ProjectionViewer implements IPropertyChangeLi
/**
* Creates new source viewer.
* @param editor
* @param parent
* @param ruler
* @param styles
* @param fOverviewRuler
* @param isOverviewRulerShowing
* @param styles
*/
public CSourceViewer(
CEditor editor, Composite parent,
IVerticalRuler ruler,
int styles,
IOverviewRuler fOverviewRuler,
boolean isOverviewRulerShowing) {
public CSourceViewer(Composite parent, IVerticalRuler ruler, IOverviewRuler fOverviewRuler, boolean isOverviewRulerShowing,
int styles) {
super(parent, ruler, fOverviewRuler, isOverviewRulerShowing, styles);
this.editor = editor;
}
/**
@ -149,55 +129,11 @@ public class CSourceViewer extends ProjectionViewer implements IPropertyChangeLi
return fContentAssistant;
}
public ILanguage getLanguage() {
if (editor == null) {
return null;
}
ICElement element = editor.getInputCElement();
if (element instanceof ITranslationUnit) {
try {
return ((ITranslationUnit)element).getLanguage();
} catch (CoreException e) {
CUIPlugin.getDefault().log(e);
}
} else {
// compute the language from the plain editor input
IContentType contentType = null;
IEditorInput input = editor.getEditorInput();
IFile file = ResourceUtil.getFile(input);
if (file != null) {
contentType = CCorePlugin.getContentType(file.getProject(), file.getName());
} else if (input instanceof IPathEditorInput) {
IPath path = ((IPathEditorInput)input).getPath();
contentType = CCorePlugin.getContentType(path.lastSegment());
} else {
ILocationProvider locationProvider = (ILocationProvider)input.getAdapter(ILocationProvider.class);
if (locationProvider != null) {
IPath path = locationProvider.getPath(input);
contentType = CCorePlugin.getContentType(path.lastSegment());
}
}
if (contentType != null) {
try {
return LanguageManager.getInstance().getLanguage(contentType);
} catch (CoreException exc) {
CUIPlugin.getDefault().log(exc.getStatus());
}
}
}
return null;
}
/**
* @see org.eclipse.jface.text.source.SourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration)
*/
public void configure(SourceViewerConfiguration configuration)
{
/*
* Prevent access to colors disposed in unconfigure(), see:
* https://bugs.eclipse.org/bugs/show_bug.cgi?id=53641
* https://bugs.eclipse.org/bugs/show_bug.cgi?id=86177
* @see ISourceViewer#configure(SourceViewerConfiguration)
*/
public void configure(SourceViewerConfiguration configuration) {
// Prevent access to colors disposed in unconfigure().
StyledText textWidget= getTextWidget();
if (textWidget != null && !textWidget.isDisposed()) {
Color foregroundColor= textWidget.getForeground();
@ -209,12 +145,13 @@ public class CSourceViewer extends ProjectionViewer implements IPropertyChangeLi
}
super.configure(configuration);
if (configuration instanceof CSourceViewerConfiguration)
{
fOutlinePresenter = ((CSourceViewerConfiguration) configuration).getOutlinePresenter(editor);
if (configuration instanceof CSourceViewerConfiguration) {
CSourceViewerConfiguration cConfiguration= (CSourceViewerConfiguration)configuration;
fOutlinePresenter= cConfiguration.getOutlinePresenter(this);
if (fOutlinePresenter != null)
fOutlinePresenter.install(this);
editor = (CEditor) cConfiguration.getEditor();
}
if (fPreferenceStore != null) {
fPreferenceStore.addPropertyChangeListener(this);
initializeViewerColors();
@ -304,8 +241,7 @@ public class CSourceViewer extends ProjectionViewer implements IPropertyChangeLi
/**
* @see org.eclipse.jface.text.source.SourceViewer#unconfigure()
*/
public void unconfigure()
{
public void unconfigure() {
if (fOutlinePresenter != null) {
fOutlinePresenter.uninstall();
fOutlinePresenter= null;
@ -376,7 +312,7 @@ public class CSourceViewer extends ProjectionViewer implements IPropertyChangeLi
case CONTENTASSIST_PROPOSALS:
{
String msg= fContentAssistant.showPossibleCompletions();
this.editor.setStatusLineErrorMessage(msg);
editor.setStatusLineErrorMessage(msg);
return;
}
case SHOW_OUTLINE:
@ -391,10 +327,8 @@ public class CSourceViewer extends ProjectionViewer implements IPropertyChangeLi
/**
* @see org.eclipse.jface.text.source.projection.ProjectionViewer#canDoOperation(int)
*/
public boolean canDoOperation(int operation)
{
if (operation == SHOW_OUTLINE)
{
public boolean canDoOperation(int operation) {
if (operation == SHOW_OUTLINE) {
return fOutlinePresenter != null;
}
return super.canDoOperation(operation);

View file

@ -54,6 +54,12 @@ public interface ICEditorActionDefinitionIds extends ITextEditorActionDefinition
*/
public static final String JOIN_LINES= "org.eclipse.cdt.ui.edit.text.c.join.lines"; //$NON-NLS-1$
/**
* Action definition ID of the source -> indent action
* (value <code>"org.eclipse.cdt.ui.edit.text.c.indent"</code>).
*/
public static final String INDENT = "org.eclipse.cdt.ui.edit.text.c.indent"; //$NON-NLS-1$
/**
* Action definition ID of the source -> format action
* (value <code>"org.eclipse.cdt.ui.edit.text.c.format"</code>).

View file

@ -0,0 +1,477 @@
/*******************************************************************************
* Copyright (c) 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.ui.editor;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.jface.text.source.ILineRange;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.ui.text.ICPartitions;
import org.eclipse.cdt.internal.corext.util.CodeFormatterUtil;
import org.eclipse.cdt.internal.ui.text.CHeuristicScanner;
import org.eclipse.cdt.internal.ui.text.CIndenter;
/**
* Utility that indents a number of lines in a document.
*/
public final class IndentUtil {
private static final String SLASHES= "//"; //$NON-NLS-1$
/**
* The result of an indentation operation. The result may be passed to
* subsequent calls to
* {@link IndentUtil#indentLines(IDocument, ILineRange, ICProject, IndentResult) indentLines}
* to obtain consistent results with respect to the indentation of
* line-comments.
*/
public static final class IndentResult {
private IndentResult(boolean[] commentLines) {
commentLinesAtColumnZero= commentLines;
}
private boolean[] commentLinesAtColumnZero;
private boolean hasChanged;
private int leftmostLine= -1;
/**
* Returns <code>true</code> if the indentation operation changed the
* document, <code>false</code> if not.
* @return <code>true</code> if the document was changed
*/
public boolean hasChanged() {
return hasChanged;
}
}
private IndentUtil() {
// do not instantiate
}
/**
* Indents the line range specified by <code>lines</code> in
* <code>document</code>. The passed C project may be
* <code>null</code>, it is used solely to obtain formatter preferences.
*
* @param document the document to be changed
* @param lines the line range to be indented
* @param project the C project to get the formatter preferences from, or
* <code>null</code> if global preferences should be used
* @param result the result from a previous call to <code>indentLines</code>,
* in order to maintain comment line properties, or <code>null</code>.
* Note that the passed result may be changed by the call.
* @return an indent result that may be queried for changes and can be
* reused in subsequent indentation operations
* @throws BadLocationException if <code>lines</code> is not a valid line
* range on <code>document</code>
*/
public static IndentResult indentLines(IDocument document, ILineRange lines, ICProject project, IndentResult result) throws BadLocationException {
int numberOfLines= lines.getNumberOfLines();
if (numberOfLines < 1)
return new IndentResult(null);
result= reuseOrCreateToken(result, numberOfLines);
CHeuristicScanner scanner= new CHeuristicScanner(document);
CIndenter indenter= new CIndenter(document, scanner, project);
boolean changed= false;
int tabSize= CodeFormatterUtil.getTabWidth(project);
for (int line= lines.getStartLine(), last= line + numberOfLines, i= 0; line < last; line++) {
changed |= indentLine(document, line, indenter, scanner, result.commentLinesAtColumnZero, i++, tabSize);
}
result.hasChanged= changed;
return result;
}
/**
* Shifts the line range specified by <code>lines</code> in
* <code>document</code>. The amount that the lines get shifted
* are determined by the first line in the range, all subsequent
* lines are adjusted accordingly. The passed C project may be
* <code>null</code>, it is used solely to obtain formatter
* preferences.
*
* @param document the document to be changed
* @param lines the line range to be shifted
* @param project the C project to get the formatter preferences
* from, or <code>null</code> if global preferences should
* be used
* @param result the result from a previous call to
* <code>shiftLines</code>, in order to maintain comment
* line properties, or <code>null</code>. Note that the
* passed result may be changed by the call.
* @return an indent result that may be queried for changes and can
* be reused in subsequent indentation operations
* @throws BadLocationException if <code>lines</code> is not a
* valid line range on <code>document</code>
*/
public static IndentResult shiftLines(IDocument document, ILineRange lines, ICProject project, IndentResult result) throws BadLocationException {
int numberOfLines= lines.getNumberOfLines();
if (numberOfLines < 1)
return new IndentResult(null);
result= reuseOrCreateToken(result, numberOfLines);
result.hasChanged= false;
CHeuristicScanner scanner= new CHeuristicScanner(document);
CIndenter indenter= new CIndenter(document, scanner, project);
String current= getCurrentIndent(document, lines.getStartLine());
StringBuffer correct= indenter.computeIndentation(document.getLineOffset(lines.getStartLine()));
if (correct == null)
return result; // bail out
int tabSize= CodeFormatterUtil.getTabWidth(project);
StringBuffer addition= new StringBuffer();
int difference= subtractIndent(correct, current, addition, tabSize);
if (difference == 0)
return result;
if (result.leftmostLine == -1)
result.leftmostLine= getLeftMostLine(document, lines, tabSize);
int maxReduction= computeVisualLength(getCurrentIndent(document, result.leftmostLine + lines.getStartLine()), tabSize);
if (difference > 0) {
for (int line= lines.getStartLine(), last= line + numberOfLines, i= 0; line < last; line++)
addIndent(document, line, addition, result.commentLinesAtColumnZero, i++);
} else {
int reduction= Math.min(-difference, maxReduction);
for (int line= lines.getStartLine(), last= line + numberOfLines, i= 0; line < last; line++)
cutIndent(document, line, reduction, tabSize, result.commentLinesAtColumnZero, i++);
}
result.hasChanged= true;
return result;
}
/**
* Indents line <code>line</code> in <code>document</code> with <code>indent</code>.
* Leaves leading comment signs alone.
*
* @param document the document
* @param line the line
* @param indent the indentation to insert
* @param commentlines
* @throws BadLocationException on concurrent document modification
*/
private static void addIndent(IDocument document, int line, CharSequence indent, boolean[] commentlines, int relative) throws BadLocationException {
IRegion region= document.getLineInformation(line);
int insert= region.getOffset();
int endOffset= region.getOffset() + region.getLength();
// go behind line comments
if (!commentlines[relative]) {
while (insert < endOffset - 2 && document.get(insert, 2).equals(SLASHES))
insert += 2;
}
// insert indent
document.replace(insert, 0, indent.toString());
}
/**
* Cuts the visual equivalent of <code>toDelete</code> characters out of the
* indentation of line <code>line</code> in <code>document</code>. Leaves
* leading comment signs alone.
*
* @param document the document
* @param line the line
* @param toDelete the number of space equivalents to delete.
* @throws BadLocationException on concurrent document modification
*/
private static void cutIndent(IDocument document, int line, int toDelete, int tabSize, boolean[] commentLines, int relative) throws BadLocationException {
IRegion region= document.getLineInformation(line);
int from= region.getOffset();
int endOffset= region.getOffset() + region.getLength();
// go behind line comments
while (from < endOffset - 2 && document.get(from, 2).equals(SLASHES))
from += 2;
int to= from;
while (toDelete > 0 && to < endOffset) {
char ch= document.getChar(to);
if (!Character.isWhitespace(ch))
break;
toDelete -= computeVisualLength(ch, tabSize);
if (toDelete >= 0)
to++;
else
break;
}
if (endOffset > to + 1 && document.get(to, 2).equals(SLASHES))
commentLines[relative]= true;
document.replace(from, to - from, null);
}
/**
* Computes the difference of two indentations and returns the difference in
* length of current and correct. If the return value is positive, <code>addition</code>
* is initialized with a substring of that length of <code>correct</code>.
*
* @param correct the correct indentation
* @param current the current indentation (migth contain non-whitespace)
* @param difference a string buffer - if the return value is positive, it will be cleared and set to the substring of <code>current</code> of that length
* @return the difference in lenght of <code>correct</code> and <code>current</code>
*/
private static int subtractIndent(CharSequence correct, CharSequence current, StringBuffer difference, int tabSize) {
int c1= computeVisualLength(correct, tabSize);
int c2= computeVisualLength(current, tabSize);
int diff= c1 - c2;
if (diff <= 0)
return diff;
difference.setLength(0);
int len= 0, i= 0;
while (len < diff) {
char c= correct.charAt(i++);
difference.append(c);
len += computeVisualLength(c, tabSize);
}
return diff;
}
private static int computeVisualLength(char ch, int tabSize) {
if (ch == '\t')
return tabSize;
else
return 1;
}
/**
* Returns the visual length of a given <code>CharSequence</code> taking into
* account the visual tabulator length.
*
* @param seq the string to measure
* @return the visual length of <code>seq</code>
*/
private static int computeVisualLength(CharSequence seq, int tablen) {
int size= 0;
for (int i= 0; i < seq.length(); i++) {
char ch= seq.charAt(i);
if (ch == '\t') {
if (tablen != 0)
size += tablen - size % tablen;
// else: size stays the same
} else {
size++;
}
}
return size;
}
/**
* Returns the indentation of the line <code>line</code> in <code>document</code>.
* The returned string may contain pairs of leading slashes that are considered
* part of the indentation. The space before the asterix in a javadoc-like
* comment is not considered part of the indentation.
*
* @param document the document
* @param line the line
* @return the indentation of <code>line</code> in <code>document</code>
* @throws BadLocationException if the document is changed concurrently
*/
private static String getCurrentIndent(IDocument document, int line) throws BadLocationException {
IRegion region= document.getLineInformation(line);
int from= region.getOffset();
int endOffset= region.getOffset() + region.getLength();
// go behind line comments
int to= from;
while (to < endOffset - 2 && document.get(to, 2).equals(SLASHES))
to += 2;
while (to < endOffset) {
char ch= document.getChar(to);
if (!Character.isWhitespace(ch))
break;
to++;
}
// don't count the space before javadoc like, asterix-style comment lines
if (to > from && to < endOffset - 1 && document.get(to - 1, 2).equals(" *")) { //$NON-NLS-1$
String type= TextUtilities.getContentType(document, ICPartitions.C_PARTITIONING, to, true);
if (type.equals(ICPartitions.C_MULTI_LINE_COMMENT))
to--;
}
return document.get(from, to - from);
}
private static int getLeftMostLine(IDocument document, ILineRange lines, int tabSize) throws BadLocationException {
int numberOfLines= lines.getNumberOfLines();
int first= lines.getStartLine();
int minLine= -1;
int minIndent= Integer.MAX_VALUE;
for (int line= 0; line < numberOfLines; line++) {
int length= computeVisualLength(getCurrentIndent(document, line + first), tabSize);
if (length < minIndent) {
minIndent= length;
minLine= line;
}
}
return minLine;
}
private static IndentResult reuseOrCreateToken(IndentResult token, int numberOfLines) {
if (token == null)
token= new IndentResult(new boolean[numberOfLines]);
else if (token.commentLinesAtColumnZero == null)
token.commentLinesAtColumnZero= new boolean[numberOfLines];
else if (token.commentLinesAtColumnZero.length != numberOfLines) {
boolean[] commentBooleans= new boolean[numberOfLines];
System.arraycopy(token.commentLinesAtColumnZero, 0, commentBooleans, 0, Math.min(numberOfLines, token.commentLinesAtColumnZero.length));
token.commentLinesAtColumnZero= commentBooleans;
}
return token;
}
/**
* Indents a single line using the java heuristic scanner. Multi line comments
* are indented as specified by the <code>CDocAutoIndentStrategy</code>.
*
* @param document the document
* @param line the line to be indented
* @param indenter the java indenter
* @param scanner the heuristic scanner
* @param commentLines the indent token comment booleans
* @param lineIndex the zero-based line index
* @return <code>true</code> if the document was modified,
* <code>false</code> if not
* @throws BadLocationException if the document got changed concurrently
*/
private static boolean indentLine(IDocument document, int line, CIndenter indenter, CHeuristicScanner scanner, boolean[] commentLines, int lineIndex, int tabSize) throws BadLocationException {
IRegion currentLine= document.getLineInformation(line);
final int offset= currentLine.getOffset();
int wsStart= offset; // where we start searching for non-WS; after the "//" in single line comments
String indent= null;
if (offset < document.getLength()) {
ITypedRegion partition= TextUtilities.getPartition(document, ICPartitions.C_PARTITIONING, offset, true);
ITypedRegion startingPartition= TextUtilities.getPartition(document, ICPartitions.C_PARTITIONING, offset, false);
String type= partition.getType();
if (type.equals(ICPartitions.C_MULTI_LINE_COMMENT)) {
indent= computeCdocIndent(document, line, scanner, startingPartition);
} else if (!commentLines[lineIndex] && startingPartition.getOffset() == offset && startingPartition.getType().equals(ICPartitions.C_SINGLE_LINE_COMMENT)) {
return false;
}
}
// standard java indentation
if (indent == null) {
StringBuffer computed= indenter.computeIndentation(offset);
if (computed != null)
indent= computed.toString();
else
indent= new String();
}
// change document:
// get current white space
int lineLength= currentLine.getLength();
int end= scanner.findNonWhitespaceForwardInAnyPartition(wsStart, offset + lineLength);
if (end == CHeuristicScanner.NOT_FOUND)
end= offset + lineLength;
int length= end - offset;
String currentIndent= document.get(offset, length);
// memorize the fact that a line is a single line comment (but not at column 0) and should be treated like code
// as opposed to commented out code, which should keep its slashes at column 0
if (length > 0) {
ITypedRegion partition= TextUtilities.getPartition(document, ICPartitions.C_PARTITIONING, end, false);
if (partition.getOffset() == end && ICPartitions.C_SINGLE_LINE_COMMENT.equals(partition.getType())) {
commentLines[lineIndex]= true;
}
}
// only change the document if it is a real change
if (!indent.equals(currentIndent)) {
document.replace(offset, length, indent);
return true;
}
return false;
}
/**
* Computes and returns the indentation for a javadoc line. The line
* must be inside a javadoc comment.
*
* @param document the document
* @param line the line in document
* @param scanner the scanner
* @param partition the comment partition
* @return the indent, or <code>null</code> if not computable
* @throws BadLocationException
*/
private static String computeCdocIndent(IDocument document, int line, CHeuristicScanner scanner, ITypedRegion partition) throws BadLocationException {
if (line == 0) // impossible - the first line is never inside a javadoc comment
return null;
// don't make any assumptions if the line does not start with \s*\* - it might be
// commented out code, for which we don't want to change the indent
final IRegion lineInfo= document.getLineInformation(line);
final int lineStart= lineInfo.getOffset();
final int lineLength= lineInfo.getLength();
final int lineEnd= lineStart + lineLength;
int nonWS= scanner.findNonWhitespaceForwardInAnyPartition(lineStart, lineEnd);
if (nonWS == CHeuristicScanner.NOT_FOUND || document.getChar(nonWS) != '*') {
if (nonWS == CHeuristicScanner.NOT_FOUND)
return document.get(lineStart, lineLength);
return document.get(lineStart, nonWS - lineStart);
}
// take the indent from the previous line and reuse
IRegion previousLine= document.getLineInformation(line - 1);
int previousLineStart= previousLine.getOffset();
int previousLineLength= previousLine.getLength();
int previousLineEnd= previousLineStart + previousLineLength;
StringBuffer buf= new StringBuffer();
int previousLineNonWS= scanner.findNonWhitespaceForwardInAnyPartition(previousLineStart, previousLineEnd);
if (previousLineNonWS == CHeuristicScanner.NOT_FOUND || document.getChar(previousLineNonWS) != '*') {
// align with the comment start if the previous line is not an asterix line
previousLine= document.getLineInformationOfOffset(partition.getOffset());
previousLineStart= previousLine.getOffset();
previousLineLength= previousLine.getLength();
previousLineEnd= previousLineStart + previousLineLength;
previousLineNonWS= scanner.findNonWhitespaceForwardInAnyPartition(previousLineStart, previousLineEnd);
if (previousLineNonWS == CHeuristicScanner.NOT_FOUND)
previousLineNonWS= previousLineEnd;
// add the initial space
// TODO this may be controlled by a formatter preference in the future
buf.append(' ');
}
String indentation= document.get(previousLineStart, previousLineNonWS - previousLineStart);
buf.insert(0, indentation);
return buf.toString();
}
}

View file

@ -28,7 +28,7 @@ import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.ui.text.ICPartitions;
import org.eclipse.cdt.internal.ui.text.CPresentationReconciler;
import org.eclipse.cdt.internal.ui.text.CSourceViewerConfiguration;
@ -294,8 +294,7 @@ public class SemanticHighlightingManager implements IPropertyChangeListener {
fColorManager= colorManager;
fPreferenceStore= preferenceStore;
if (fEditor != null) {
fConfiguration= new CSourceViewerConfiguration(CUIPlugin.getDefault().getTextTools(), fEditor);
// fConfiguration= new CSourceViewerConfiguration(colorManager, preferenceStore, editor, ICPartitions.C_PARTITIONING);
fConfiguration= new CSourceViewerConfiguration(colorManager, preferenceStore, editor, ICPartitions.C_PARTITIONING);
fPresentationReconciler= (CPresentationReconciler) fConfiguration.getPresentationReconciler(sourceViewer);
} else {
fConfiguration= null;

View file

@ -7,6 +7,7 @@
*
* Contributors:
* IBM Corporation - initial API and implementation
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences;

View file

@ -7,6 +7,7 @@
*
* Contributors:
* IBM Corporation - initial API and implementation
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences;

View file

@ -57,8 +57,6 @@ import org.eclipse.ui.dialogs.PreferencesUtil;
import org.eclipse.ui.editors.text.EditorsUI;
import org.eclipse.ui.texteditor.ChainedPreferenceStore;
import org.eclipse.cdt.core.dom.ast.gnu.cpp.GPPLanguage;
import org.eclipse.cdt.core.model.ILanguage;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.ui.PreferenceConstants;
import org.eclipse.cdt.ui.text.ICPartitions;
@ -69,7 +67,6 @@ import org.eclipse.cdt.internal.ui.editor.SemanticHighlightingManager;
import org.eclipse.cdt.internal.ui.editor.SemanticHighlightings;
import org.eclipse.cdt.internal.ui.editor.SemanticHighlightingManager.HighlightedRange;
import org.eclipse.cdt.internal.ui.text.CSourceViewerConfiguration;
import org.eclipse.cdt.internal.ui.text.CTextTools;
import org.eclipse.cdt.internal.ui.text.IColorManager;
import org.eclipse.cdt.internal.ui.text.util.CColorManager;
import org.eclipse.cdt.internal.ui.util.PixelConverter;
@ -335,7 +332,6 @@ class CEditorColoringConfigurationBlock extends AbstractConfigurationBlock {
* The font metrics.
*/
private FontMetrics fFontMetrics;
private CTextTools fTextTools;
public CEditorColoringConfigurationBlock(OverlayPreferenceStore store) {
super(store);
@ -469,10 +465,6 @@ class CEditorColoringConfigurationBlock extends AbstractConfigurationBlock {
public void dispose() {
uninstallSemanticHighlighting();
fColorManager.dispose();
if (fTextTools != null) {
fTextTools.dispose();
fTextTools= null;
}
super.dispose();
}
@ -748,14 +740,9 @@ class CEditorColoringConfigurationBlock extends AbstractConfigurationBlock {
IPreferenceStore generalTextStore= EditorsUI.getPreferenceStore();
IPreferenceStore store= new ChainedPreferenceStore(new IPreferenceStore[] { getPreferenceStore(), generalTextStore });
fTextTools= new CTextTools(store, null, false);
fPreviewViewer = new CSourceViewer(parent, null, null, false, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER, store) {
public ILanguage getLanguage() {
return GPPLanguage.getDefault();
}
};
fPreviewViewer = new CSourceViewer(parent, null, null, false, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER, store);
fPreviewViewer.setPreferenceStore(store);
CSourceViewerConfiguration configuration = new CSourceViewerConfiguration(fTextTools, null);
CSourceViewerConfiguration configuration = new CSourceViewerConfiguration(fColorManager, store, null, ICPartitions.C_PARTITIONING);
fPreviewViewer.configure(configuration);
Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT);
fPreviewViewer.getTextWidget().setFont(font);
@ -764,7 +751,7 @@ class CEditorColoringConfigurationBlock extends AbstractConfigurationBlock {
String content= loadPreviewContentFromFile("ColorSettingPreviewCode.txt"); //$NON-NLS-1$
IDocument document= new Document(content);
fTextTools.setupCDocumentPartitioner(document, ICPartitions.C_PARTITIONING);
CUIPlugin.getDefault().getTextTools().setupCDocumentPartitioner(document, ICPartitions.C_PARTITIONING);
fPreviewViewer.setDocument(document);
installSemanticHighlighting();

View file

@ -83,7 +83,6 @@ public class CEditorPreferencePage extends AbstractPreferencePage implements IWo
overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CEditor.MATCHING_BRACKETS));
overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, CEditor.INACTIVE_CODE_COLOR));
overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CEditor.INACTIVE_CODE_ENABLE));
overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CEditor.SPACES_FOR_TABS));
overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.ENSURE_NEWLINE_AT_EOF));
OverlayPreferenceStore.OverlayKey[] keys = new OverlayPreferenceStore.OverlayKey[overlayKeys.size()];
@ -111,8 +110,6 @@ public class CEditorPreferencePage extends AbstractPreferencePage implements IWo
store.setDefault(CEditor.INACTIVE_CODE_ENABLE, true);
PreferenceConverter.setDefault(store, CEditor.INACTIVE_CODE_COLOR, new RGB(224, 224, 224));
store.setDefault(CEditor.SPACES_FOR_TABS, false);
}
/*
@ -150,9 +147,6 @@ public class CEditorPreferencePage extends AbstractPreferencePage implements IWo
label = PreferencesMessages.CEditorPreferencePage_behaviorPage_inactiveCode;
addCheckBox(behaviorComposite, label, CEditor.INACTIVE_CODE_ENABLE, 0);
label = PreferencesMessages.CEditorPreferencePage_behaviorPage_tabSpace;
addCheckBox(behaviorComposite, label, CEditor.SPACES_FOR_TABS, 0);
label = PreferencesMessages.CEditorPreferencePage_behaviorPage_ensureNewline;
addCheckBox(behaviorComposite, label, PreferenceConstants.ENSURE_NEWLINE_AT_EOF, 0);

View file

@ -58,8 +58,8 @@ public class CSourcePreviewerUpdater {
* @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (configuration.affectsBehavior(event)) {
configuration.adaptToPreferenceChange(event);
if (configuration.affectsTextPresentation(event)) {
configuration.handlePropertyChangeEvent(event);
viewer.invalidateTextPresentation();
}
}

View file

@ -7,85 +7,147 @@
*
* Contributors:
* QNX Software Systems - Initial API and implementation
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences;
import org.eclipse.cdt.internal.ui.ICHelpContextIds;
import org.eclipse.cdt.internal.ui.dialogs.StatusUtil;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.ui.dialogs.CodeFormatterBlock;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.resources.IProject;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.jface.preference.IPreferencePageContainer;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
import org.eclipse.ui.preferences.IWorkingCopyManager;
import org.eclipse.ui.preferences.WorkingCopyManager;
/**
*
import org.eclipse.cdt.internal.ui.ICHelpContextIds;
import org.eclipse.cdt.internal.ui.preferences.formatter.CodeFormatterConfigurationBlock;
/*
* The page to configure the code formatter options.
*/
public class CodeFormatterPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
public class CodeFormatterPreferencePage extends PropertyAndPreferencePage {
CodeFormatterBlock fCodeFormatterBlock;
public static final String PREF_ID= "org.eclipse.cdt.ui.preferences.CodeFormatterPreferencePage"; //$NON-NLS-1$
public static final String PROP_ID= "org.eclipse.cdt.ui.propertyPages.CodeFormatterPreferencePage"; //$NON-NLS-1$
private CodeFormatterConfigurationBlock fConfigurationBlock;
public CodeFormatterPreferencePage() {
setPreferenceStore(CUIPlugin.getDefault().getPreferenceStore());
setDescription(PreferencesMessages.CodeFormatterPreferencePage_description);
// only used when page is shown programatically
setTitle(PreferencesMessages.CodeFormatterPreferencePage_title);
//setDescription(PreferencesMessages.getString("CodeFormatterPreferencePage.description")); //$NON-NLS-1$
fCodeFormatterBlock= new CodeFormatterBlock(CUIPlugin.getDefault().getPluginPreferences());
}
/*
* @see IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
*/
public void init(IWorkbench workbench) {
}
/*
* @see PreferencePage#createContents(Composite)
*/
protected Control createContents(Composite parent) {
Composite topPane = new Composite(parent, SWT.NONE);
topPane.setLayout(new GridLayout());
topPane.setLayoutData(new GridData(GridData.FILL_BOTH));
applyDialogFont(parent);
PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), ICHelpContextIds.CODEFORMATTER_PREFERENCE_PAGE);
return fCodeFormatterBlock.createControl(topPane);
}
/*
* @see IPreferencePage#performOk()
*/
public boolean performOk() {
fCodeFormatterBlock.performOk();
return super.performOk();
}
/* (non-Javadoc)
* @see org.eclipse.jface.preference.PreferencePage#performDefaults()
* @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
*/
public void createControl(Composite parent) {
IPreferencePageContainer container= getContainer();
IWorkingCopyManager workingCopyManager;
if (container instanceof IWorkbenchPreferenceContainer) {
workingCopyManager= ((IWorkbenchPreferenceContainer) container).getWorkingCopyManager();
} else {
workingCopyManager= new WorkingCopyManager(); // non shared
}
PreferencesAccess access= PreferencesAccess.getWorkingCopyPreferences(workingCopyManager);
fConfigurationBlock= new CodeFormatterConfigurationBlock(getProject(), access);
super.createControl(parent);
PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), ICHelpContextIds.CODEFORMATTER_PREFERENCE_PAGE);
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.ui.preferences.PropertyAndPreferencePage#createPreferenceContent(org.eclipse.swt.widgets.Composite)
*/
protected Control createPreferenceContent(Composite composite) {
return fConfigurationBlock.createContents(composite);
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.ui.preferences.PropertyAndPreferencePage#hasProjectSpecificOptions(org.eclipse.core.resources.IProject)
*/
protected boolean hasProjectSpecificOptions(IProject project) {
return fConfigurationBlock.hasProjectSpecificOptions(project);
}
// /* (non-Javadoc)
// * @see org.eclipse.cdt.internal.ui.preferences.PropertyAndPreferencePage#enableProjectSpecificSettings(boolean)
// */
// protected void enableProjectSpecificSettings(boolean useProjectSpecificSettings) {
// super.enableProjectSpecificSettings(useProjectSpecificSettings);
// if (fConfigurationBlock != null) {
// fConfigurationBlock.enableProjectSpecificSettings(useProjectSpecificSettings);
// }
// }
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.ui.preferences.PropertyAndPreferencePage#getPreferencePageID()
*/
protected String getPreferencePageID() {
return PREF_ID;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.ui.preferences.PropertyAndPreferencePage#getPropertyPageID()
*/
protected String getPropertyPageID() {
return PROP_ID;
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.DialogPage#dispose()
*/
public void dispose() {
if (fConfigurationBlock != null) {
fConfigurationBlock.dispose();
}
super.dispose();
}
/* (non-Javadoc)
* @see org.eclipse.jface.preference.IPreferencePage#performDefaults()
*/
protected void performDefaults() {
fCodeFormatterBlock.performDefaults();
if (fConfigurationBlock != null) {
fConfigurationBlock.performDefaults();
}
super.performDefaults();
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener#statusChanged(org.eclipse.core.runtime.IStatus)
* @see org.eclipse.jface.preference.IPreferencePage#performOk()
*/
public void statusChanged(IStatus status) {
setValid(!status.matches(IStatus.ERROR));
StatusUtil.applyToStatusLine(this, status);
public boolean performOk() {
if (fConfigurationBlock != null && !fConfigurationBlock.performOk()) {
return false;
}
return super.performOk();
}
/* (non-Javadoc)
* @see org.eclipse.jface.preference.IPreferencePage#performOk()
*/
public void performApply() {
if (fConfigurationBlock != null) {
fConfigurationBlock.performApply();
}
super.performApply();
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.ui.preferences.PropertyAndPreferencePage#setElement(org.eclipse.core.runtime.IAdaptable)
*/
public void setElement(IAdaptable element) {
super.setElement(element);
setDescription(null); // no description for property page
}
}

View file

@ -7,6 +7,7 @@
*
* Contributors:
* IBM Corporation - initial API and implementation
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences;
@ -23,7 +24,7 @@ import org.eclipse.swt.widgets.Control;
* Clients may implement this interface.
* </p>
*
* @since 4.0
* @since 3.0
*/
public interface IPreferenceConfigurationBlock {

View file

@ -0,0 +1,124 @@
/*******************************************************************************
* Copyright (c) 2000, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.preferences.DefaultScope;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.IScopeContext;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ProjectScope;
import org.eclipse.ui.preferences.IWorkingCopyManager;
import org.osgi.service.prefs.BackingStoreException;
/**
*
*/
public class PreferencesAccess {
public static PreferencesAccess getOriginalPreferences() {
return new PreferencesAccess();
}
public static PreferencesAccess getWorkingCopyPreferences(IWorkingCopyManager workingCopyManager) {
return new WorkingCopyPreferencesAccess(workingCopyManager);
}
private PreferencesAccess() {
// can only extends in this file
}
public IScopeContext getDefaultScope() {
return new DefaultScope();
}
public IScopeContext getInstanceScope() {
return new InstanceScope();
}
public IScopeContext getProjectScope(IProject project) {
return new ProjectScope(project);
}
public void applyChanges() throws BackingStoreException {
}
private static class WorkingCopyPreferencesAccess extends PreferencesAccess {
private final IWorkingCopyManager fWorkingCopyManager;
private WorkingCopyPreferencesAccess(IWorkingCopyManager workingCopyManager) {
fWorkingCopyManager= workingCopyManager;
}
private final IScopeContext getWorkingCopyScopeContext(IScopeContext original) {
return new WorkingCopyScopeContext(fWorkingCopyManager, original);
}
public IScopeContext getDefaultScope() {
return getWorkingCopyScopeContext(super.getDefaultScope());
}
public IScopeContext getInstanceScope() {
return getWorkingCopyScopeContext(super.getInstanceScope());
}
public IScopeContext getProjectScope(IProject project) {
return getWorkingCopyScopeContext(super.getProjectScope(project));
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.ui.preferences.PreferencesAccess#applyChanges()
*/
public void applyChanges() throws BackingStoreException {
fWorkingCopyManager.applyChanges();
}
}
private static class WorkingCopyScopeContext implements IScopeContext {
private final IWorkingCopyManager fWorkingCopyManager;
private final IScopeContext fOriginal;
public WorkingCopyScopeContext(IWorkingCopyManager workingCopyManager, IScopeContext original) {
fWorkingCopyManager= workingCopyManager;
fOriginal= original;
}
/* (non-Javadoc)
* @see org.eclipse.core.runtime.preferences.IScopeContext#getName()
*/
public String getName() {
return fOriginal.getName();
}
/* (non-Javadoc)
* @see org.eclipse.core.runtime.preferences.IScopeContext#getNode(java.lang.String)
*/
public IEclipsePreferences getNode(String qualifier) {
return fWorkingCopyManager.getWorkingCopy(fOriginal.getNode(qualifier));
}
/* (non-Javadoc)
* @see org.eclipse.core.runtime.preferences.IScopeContext#getLocation()
*/
public IPath getLocation() {
return fOriginal.getLocation();
}
}
}

View file

@ -164,9 +164,6 @@ public final class PreferencesMessages extends NLS {
public static String FoldingConfigurationBlock_combo_caption;
public static String FoldingConfigurationBlock_info_no_preferences;
public static String FoldingConfigurationBlock_error_not_exist;
public static String CodeFormatterPreferencePage_title;
public static String CodeFormatterPreferencePage_selectionName;
public static String CodeFormatterPreferencePage_emptyName;
public static String PathEntryVariablePreference_explanation;
public static String PathEntryVariableDialog_shellTitle_newVariable;
public static String PathEntryVariableDialog_shellTitle_existingVariable;
@ -194,6 +191,32 @@ public final class PreferencesMessages extends NLS {
public static String IndexerPrefs_description;
public static String ProposalFilterPreferencesUtil_defaultFilterName;
public static String CEditorPreferencePage_typing_tabTitle;
public static String CEditorPreferencePage_typing_description;
public static String CEditorPreferencePage_closeStrings;
public static String CEditorPreferencePage_closeBrackets;
public static String CEditorPreferencePage_closeAngularBrackets;
public static String CEditorPreferencePage_closeBraces;
public static String CEditorPreferencePage_wrapStrings;
public static String CEditorPreferencePage_escapeStrings;
public static String CEditorPreferencePage_smartPaste;
public static String CEditorPreferencePage_typing_smartTab;
public static String SmartTypingConfigurationBlock_autoclose_title;
public static String SmartTypingConfigurationBlock_tabs_title;
public static String SmartTypingConfigurationBlock_tabs_message_tab_text;
public static String SmartTypingConfigurationBlock_tabs_message_others_text;
public static String SmartTypingConfigurationBlock_tabs_message_tooltip;
public static String SmartTypingConfigurationBlock_tabs_message_spaces;
public static String SmartTypingConfigurationBlock_tabs_message_tabs;
public static String SmartTypingConfigurationBlock_tabs_message_tabsAndSpaces;
public static String SmartTypingConfigurationBlock_pasting_title;
public static String SmartTypingConfigurationBlock_strings_title;
public static String CodeFormatterPreferencePage_title;
public static String CodeFormatterPreferencePage_description;
static {
NLS.initializeMessages(BUNDLE_NAME, PreferencesMessages.class);
}

View file

@ -190,10 +190,37 @@ FoldingConfigurationBlock_combo_caption= Select folding to &use:
FoldingConfigurationBlock_info_no_preferences= The selected folding provider did not provide a preference control
FoldingConfigurationBlock_error_not_exist= The selected folding provider does not exist
# Smart typing block
SmartTypingConfigurationBlock_autoclose_title=Automatically close
SmartTypingConfigurationBlock_tabs_title=Tabulators
# The argument will be replaced by the tab display size
SmartTypingConfigurationBlock_tabs_message_tab_text=The tab display value (currently {0}) and whether spaces are used to indent lines are configured on the <a>code style preference page</a>. The current indentation mode uses tabs.
# The first argument will be replaced by the tab display size, the second by the indent size and the third by the NLSed string of 'SmartTypingConfigurationBlock_tabs_message_spaces' or 'SmartTypingConfigurationBlock_tabs_message_tabs' (see below)
SmartTypingConfigurationBlock_tabs_message_others_text=The tab display value (currently {0}) and whether spaces are used to indent lines are configured on the <a>code style preference page</a>. The current indentation size is {1}, using {2}.
SmartTypingConfigurationBlock_tabs_message_tooltip=Go to the code style preference page
SmartTypingConfigurationBlock_tabs_message_spaces=spaces
SmartTypingConfigurationBlock_tabs_message_tabs=tabs
SmartTypingConfigurationBlock_tabs_message_tabsAndSpaces=tabs and spaces
SmartTypingConfigurationBlock_pasting_title=When pasting
SmartTypingConfigurationBlock_strings_title=In string literals
CEditorPreferencePage_empty_input=Empty input
CEditorPreferencePage_invalid_input="{0}" is not a valid input.
CEditorPreferencePage_typing_tabTitle=T&yping
CEditorPreferencePage_typing_description=Enable these typing aids in Smart Insert mode:
CEditorPreferencePage_closeStrings="&Strings"
CEditorPreferencePage_closeBrackets=(&Parentheses) and [square] brackets
CEditorPreferencePage_closeAngularBrackets=<A&ngle> brackets
CEditorPreferencePage_closeBraces={B&races}
CEditorPreferencePage_wrapStrings=&Wrap automatically
CEditorPreferencePage_escapeStrings=Escape text w&hen pasting into a string literal
CEditorPreferencePage_smartPaste=Adjust &indentation
CEditorPreferencePage_typing_smartTab= &Tab key indents the current line
# Code Formatting
CodeFormatterPreferencePage_title=Code Formatter
CodeFormatterPreferencePage_selectionName=Formatters:
CodeFormatterPreferencePage_emptyName=(NONE)
CodeFormatterPreferencePage_title=Code Style
CodeFormatterPreferencePage_description=Sele&ct a profile:
# --- Linked Resources ---
PathEntryVariablePreference_explanation = PathEntry variables.

View file

@ -0,0 +1,287 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences;
import java.util.Map;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.dialogs.ControlEnableState;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Link;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.IWorkbenchPropertyPage;
import org.eclipse.ui.dialogs.PreferencesUtil;
import org.eclipse.cdt.internal.ui.dialogs.IStatusChangeListener;
import org.eclipse.cdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.cdt.internal.ui.dialogs.StatusUtil;
/**
* Base for project property and preference pages
*/
public abstract class PropertyAndPreferencePage extends PreferencePage implements IWorkbenchPreferencePage, IWorkbenchPropertyPage {
private Control fConfigurationBlockControl;
private ControlEnableState fBlockEnableState;
private Link fChangeWorkspaceSettings;
// private SelectionButtonDialogField fUseProjectSettings;
private IStatus fBlockStatus;
private Composite fParentComposite;
private IProject fProject; // project or null
private Map fData; // page data
public static final String DATA_NO_LINK= "PropertyAndPreferencePage.nolink"; //$NON-NLS-1$
public PropertyAndPreferencePage() {
fBlockStatus= new StatusInfo();
fBlockEnableState= null;
fProject= null;
fData= null;
}
protected abstract Control createPreferenceContent(Composite composite);
protected abstract boolean hasProjectSpecificOptions(IProject project);
protected abstract String getPreferencePageID();
protected abstract String getPropertyPageID();
protected boolean supportsProjectSpecificOptions() {
return getPropertyPageID() != null;
}
protected boolean offerLink() {
return fData == null || !Boolean.TRUE.equals(fData.get(DATA_NO_LINK));
}
// TODO: Project specific settings are not supported yet.
//protected Label createDescriptionLabel(Composite parent) {
// fParentComposite= parent;
// if (isProjectPreferencePage()) {
// Composite composite= new Composite(parent, SWT.NONE);
// composite.setFont(parent.getFont());
// GridLayout layout= new GridLayout();
// layout.marginHeight= 0;
// layout.marginWidth= 0;
// layout.numColumns= 2;
// composite.setLayout(layout);
// composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
//
// IDialogFieldListener listener= new IDialogFieldListener() {
// public void dialogFieldChanged(DialogField field) {
// enableProjectSpecificSettings(((SelectionButtonDialogField)field).isSelected());
// }
// };
//
// fUseProjectSettings= new SelectionButtonDialogField(SWT.CHECK);
// fUseProjectSettings.setDialogFieldListener(listener);
// fUseProjectSettings.setLabelText(PreferencesMessages.PropertyAndPreferencePage_useprojectsettings_label);
// fUseProjectSettings.doFillIntoGrid(composite, 1);
// LayoutUtil.setHorizontalGrabbing(fUseProjectSettings.getSelectionButton(null));
//
// if (offerLink()) {
// fChangeWorkspaceSettings= createLink(composite, PreferencesMessages.PropertyAndPreferencePage_useworkspacesettings_change);
// fChangeWorkspaceSettings.setLayoutData(new GridData(SWT.END, SWT.CENTER, false, false));
// } else {
// LayoutUtil.setHorizontalSpan(fUseProjectSettings.getSelectionButton(null), 2);
// }
//
// Label horizontalLine= new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL);
// horizontalLine.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false, 2, 1));
// horizontalLine.setFont(composite.getFont());
// } else if (supportsProjectSpecificOptions() && offerLink()) {
// fChangeWorkspaceSettings= createLink(parent, PreferencesMessages.PropertyAndPreferencePage_showprojectspecificsettings_label);
// fChangeWorkspaceSettings.setLayoutData(new GridData(SWT.END, SWT.CENTER, true, false));
// }
//
// return super.createDescriptionLabel(parent);
// }
/*
* @see org.eclipse.jface.preference.IPreferencePage#createContents(Composite)
*/
protected Control createContents(Composite parent) {
Composite composite= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
composite.setLayout(layout);
composite.setFont(parent.getFont());
GridData data= new GridData(GridData.FILL, GridData.FILL, true, true);
fConfigurationBlockControl= createPreferenceContent(composite);
fConfigurationBlockControl.setLayoutData(data);
// TODO: Project specific settings are not supported yet.
// if (isProjectPreferencePage()) {
// boolean useProjectSettings= hasProjectSpecificOptions(getProject());
// enableProjectSpecificSettings(useProjectSettings);
// }
Dialog.applyDialogFont(composite);
return composite;
}
protected boolean useProjectSettings() {
// TODO: Project specific settings are not supported yet.
// return isProjectPreferencePage() && fUseProjectSettings != null && fUseProjectSettings.isSelected();
return false;
}
protected boolean isProjectPreferencePage() {
return fProject != null;
}
protected IProject getProject() {
return fProject;
}
protected final void openWorkspacePreferences(Object data) {
String id= getPreferencePageID();
PreferencesUtil.createPreferenceDialogOn(getShell(), id, new String[] { id }, data).open();
}
protected final void openProjectProperties(IProject project, Object data) {
String id= getPropertyPageID();
if (id != null) {
PreferencesUtil.createPropertyDialogOn(getShell(), project, id, new String[] { id }, data).open();
}
}
// TODO: Project specific settings are not supported yet.
// protected void enableProjectSpecificSettings(boolean useProjectSpecificSettings) {
// fUseProjectSettings.setSelection(useProjectSpecificSettings);
// enablePreferenceContent(useProjectSpecificSettings);
// updateLinkVisibility();
// doStatusChanged();
// }
//
// private void updateLinkVisibility() {
// if (fChangeWorkspaceSettings == null || fChangeWorkspaceSettings.isDisposed()) {
// return;
// }
//
// if (isProjectPreferencePage()) {
// fChangeWorkspaceSettings.setEnabled(!useProjectSettings());
// }
// }
protected void setPreferenceContentStatus(IStatus status) {
fBlockStatus= status;
doStatusChanged();
}
/**
* Returns a new status change listener that calls {@link #setPreferenceContentStatus(IStatus)}
* when the status has changed
* @return The new listener
*/
protected IStatusChangeListener getNewStatusChangedListener() {
return new IStatusChangeListener() {
public void statusChanged(IStatus status) {
setPreferenceContentStatus(status);
}
};
}
protected IStatus getPreferenceContentStatus() {
return fBlockStatus;
}
protected void doStatusChanged() {
if (!isProjectPreferencePage() || useProjectSettings()) {
updateStatus(fBlockStatus);
} else {
updateStatus(new StatusInfo());
}
}
protected void enablePreferenceContent(boolean enable) {
if (enable) {
if (fBlockEnableState != null) {
fBlockEnableState.restore();
fBlockEnableState= null;
}
} else {
if (fBlockEnableState == null) {
fBlockEnableState= ControlEnableState.disable(fConfigurationBlockControl);
}
}
}
/*
* @see org.eclipse.jface.preference.IPreferencePage#performDefaults()
*/
protected void performDefaults() {
// TODO: Project specific settings are not supported yet.
// if (useProjectSettings()) {
// enableProjectSpecificSettings(false);
// }
super.performDefaults();
}
private void updateStatus(IStatus status) {
setValid(!status.matches(IStatus.ERROR));
StatusUtil.applyToStatusLine(this, status);
}
/* (non-Javadoc)
* @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
*/
public void init(IWorkbench workbench) {
}
/* (non-Javadoc)
* @see org.eclipse.ui.IWorkbenchPropertyPage#getElement()
*/
public IAdaptable getElement() {
return fProject;
}
/* (non-Javadoc)
* @see org.eclipse.ui.IWorkbenchPropertyPage#setElement(org.eclipse.core.runtime.IAdaptable)
*/
public void setElement(IAdaptable element) {
fProject= (IProject) element.getAdapter(IResource.class);
}
/* (non-Javadoc)
* @see org.eclipse.jface.preference.PreferencePage#applyData(java.lang.Object)
*/
public void applyData(Object data) {
if (data instanceof Map) {
fData= (Map) data;
}
if (fChangeWorkspaceSettings != null) {
if (!offerLink()) {
fChangeWorkspaceSettings.dispose();
fParentComposite.layout(true, true);
}
}
}
protected Map getData() {
return fData;
}
}

View file

@ -7,6 +7,7 @@
*
* Contributors:
* IBM Corporation - initial API and implementation
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences;

View file

@ -0,0 +1,250 @@
/*******************************************************************************
* Copyright (c) 2000, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.Assert;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
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.Link;
import org.eclipse.ui.dialogs.PreferencesUtil;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.ui.PreferenceConstants;
import org.eclipse.cdt.internal.corext.util.CodeFormatterUtil;
import org.eclipse.cdt.internal.ui.util.Messages;
/**
* Configures C Editor typing preferences.
*/
class SmartTypingConfigurationBlock extends AbstractConfigurationBlock {
public SmartTypingConfigurationBlock(OverlayPreferenceStore store) {
super(store);
store.addKeys(createOverlayStoreKeys());
}
private OverlayPreferenceStore.OverlayKey[] createOverlayStoreKeys() {
return new OverlayPreferenceStore.OverlayKey[] {
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SMART_PASTE),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CLOSE_STRINGS),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CLOSE_BRACKETS),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CLOSE_ANGULAR_BRACKETS),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CLOSE_BRACES),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_WRAP_STRINGS),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_ESCAPE_STRINGS),
// new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SMART_SEMICOLON),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SMART_TAB),
// new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SMART_OPENING_BRACE),
};
}
/**
* Creates page for mark occurrences preferences.
*
* @param parent the parent composite
* @return the control for the preference page
*/
public Control createControl(Composite parent) {
ScrolledPageContent scrolled= new ScrolledPageContent(parent, SWT.H_SCROLL | SWT.V_SCROLL);
scrolled.setExpandHorizontal(true);
scrolled.setExpandVertical(true);
Composite control= new Composite(scrolled, SWT.NONE);
GridLayout layout= new GridLayout();
control.setLayout(layout);
Composite composite;
composite= createSubsection(control, null, PreferencesMessages.SmartTypingConfigurationBlock_autoclose_title);
addAutoclosingSection(composite);
// composite= createSubsection(control, null, PreferencesMessages.SmartTypingConfigurationBlock_automove_title);
// addAutopositionSection(composite);
composite= createSubsection(control, null, PreferencesMessages.SmartTypingConfigurationBlock_tabs_title);
addTabSection(composite);
composite= createSubsection(control, null, PreferencesMessages.SmartTypingConfigurationBlock_pasting_title);
addPasteSection(composite);
composite= createSubsection(control, null, PreferencesMessages.SmartTypingConfigurationBlock_strings_title);
addStringsSection(composite);
scrolled.setContent(control);
final Point size= control.computeSize(SWT.DEFAULT, SWT.DEFAULT);
scrolled.setMinSize(size.x, size.y);
return scrolled;
}
private void addStringsSection(Composite composite) {
GridLayout layout= new GridLayout();
composite.setLayout(layout);
String label;
Button master, slave;
label= PreferencesMessages.CEditorPreferencePage_wrapStrings;
master= addCheckBox(composite, label, PreferenceConstants.EDITOR_WRAP_STRINGS, 0);
label= PreferencesMessages.CEditorPreferencePage_escapeStrings;
slave= addCheckBox(composite, label, PreferenceConstants.EDITOR_ESCAPE_STRINGS, 0);
createDependency(master, slave);
}
private void addPasteSection(Composite composite) {
GridLayout layout= new GridLayout();
composite.setLayout(layout);
String label;
label= PreferencesMessages.CEditorPreferencePage_smartPaste;
addCheckBox(composite, label, PreferenceConstants.EDITOR_SMART_PASTE, 0);
}
private void addTabSection(Composite composite) {
GridLayout layout= new GridLayout();
composite.setLayout(layout);
String label;
label= PreferencesMessages.CEditorPreferencePage_typing_smartTab;
addCheckBox(composite, label, PreferenceConstants.EDITOR_SMART_TAB, 0);
createMessage(composite);
}
// private void addAutopositionSection(Composite composite) {
// GridLayout layout= new GridLayout();
// composite.setLayout(layout);
//
// String label;
//
// label= PreferencesMessages.CEditorPreferencePage_typing_smartSemicolon;
// addCheckBox(composite, label, PreferenceConstants.EDITOR_SMART_SEMICOLON, 0);
//
// label= PreferencesMessages.CEditorPreferencePage_typing_smartOpeningBrace;
// addCheckBox(composite, label, PreferenceConstants.EDITOR_SMART_OPENING_BRACE, 0);
// }
private void addAutoclosingSection(Composite composite) {
GridLayout layout= new GridLayout();
layout.numColumns= 1;
composite.setLayout(layout);
String label;
label= PreferencesMessages.CEditorPreferencePage_closeStrings;
addCheckBox(composite, label, PreferenceConstants.EDITOR_CLOSE_STRINGS, 0);
label= PreferencesMessages.CEditorPreferencePage_closeBrackets;
addCheckBox(composite, label, PreferenceConstants.EDITOR_CLOSE_BRACKETS, 0);
label= PreferencesMessages.CEditorPreferencePage_closeAngularBrackets;
addCheckBox(composite, label, PreferenceConstants.EDITOR_CLOSE_ANGULAR_BRACKETS, 0);
label= PreferencesMessages.CEditorPreferencePage_closeBraces;
addCheckBox(composite, label, PreferenceConstants.EDITOR_CLOSE_BRACES, 0);
}
private void createMessage(final Composite composite) {
// TODO create a link with an argument, so the formatter preference page can open the
// current profile automatically.
String linkTooltip= PreferencesMessages.SmartTypingConfigurationBlock_tabs_message_tooltip;
String text;
String indentMode= CUIPlugin.getDefault().getCombinedPreferenceStore().getString(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR);
if (CCorePlugin.TAB.equals(indentMode))
text= Messages.format(PreferencesMessages.SmartTypingConfigurationBlock_tabs_message_tab_text, new String[] {Integer.toString(getTabDisplaySize())});
else
text= Messages.format(PreferencesMessages.SmartTypingConfigurationBlock_tabs_message_others_text, new String[] {Integer.toString(getTabDisplaySize()), Integer.toString(getIndentSize()), getIndentMode()});
final Link link= new Link(composite, SWT.NONE);
link.setText(text);
link.setToolTipText(linkTooltip);
GridData gd= new GridData(SWT.FILL, SWT.BEGINNING, true, false);
gd.widthHint= 300; // don't get wider initially
link.setLayoutData(gd);
link.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
PreferencesUtil.createPreferenceDialogOn(link.getShell(), "org.eclipse.cdt.ui.preferences.CodeFormatterPreferencePage", null, null); //$NON-NLS-1$
}
});
final IPreferenceStore combinedStore= CUIPlugin.getDefault().getCombinedPreferenceStore();
final IPropertyChangeListener propertyChangeListener= new IPropertyChangeListener() {
private boolean fHasRun= false;
public void propertyChange(PropertyChangeEvent event) {
if (fHasRun)
return;
if (composite.isDisposed())
return;
String property= event.getProperty();
if (DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR.equals(property)
|| DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE.equals(property)) {
fHasRun= true;
link.dispose();
createMessage(composite);
Dialog.applyDialogFont(composite);
composite.redraw();
composite.layout();
}
}
};
combinedStore.addPropertyChangeListener(propertyChangeListener);
link.addDisposeListener(new DisposeListener() {
public void widgetDisposed(org.eclipse.swt.events.DisposeEvent e) {
combinedStore.removePropertyChangeListener(propertyChangeListener);
}
});
}
private String getIndentMode() {
String indentMode= CUIPlugin.getDefault().getCombinedPreferenceStore().getString(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR);
if (CCorePlugin.SPACE.equals(indentMode))
return PreferencesMessages.SmartTypingConfigurationBlock_tabs_message_spaces;
if (CCorePlugin.TAB.equals(indentMode))
return PreferencesMessages.SmartTypingConfigurationBlock_tabs_message_tabs;
if (DefaultCodeFormatterConstants.MIXED.equals(indentMode))
return PreferencesMessages.SmartTypingConfigurationBlock_tabs_message_tabsAndSpaces;
Assert.isTrue(false, "Illegal indent mode - must not happen"); //$NON-NLS-1$
return null;
}
private int getIndentSize() {
return CodeFormatterUtil.getIndentWidth(null);
}
private int getTabDisplaySize() {
return CodeFormatterUtil.getTabWidth(null);
}
}

View file

@ -0,0 +1,59 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporatio - initial API and implementation
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.cdt.internal.ui.ICHelpContextIds;
import org.eclipse.cdt.ui.CUIPlugin;
/**
* The page for setting the editor options.
*/
public final class SmartTypingPreferencePage extends AbstractConfigurationBlockPreferencePage {
/*
* @see org.eclipse.ui.internal.editors.text.AbstractConfigureationBlockPreferencePage#getHelpId()
*/
protected String getHelpId() {
return ICHelpContextIds.C_EDITOR_TYPING_PAGE;
}
/*
* @see org.eclipse.ui.internal.editors.text.AbstractConfigurationBlockPreferencePage#setDescription()
*/
protected void setDescription() {
String description= PreferencesMessages.CEditorPreferencePage_typing_tabTitle;
setDescription(description);
}
/*
* @see org.org.eclipse.ui.internal.editors.text.AbstractConfigurationBlockPreferencePage#setPreferenceStore()
*/
protected void setPreferenceStore() {
setPreferenceStore(CUIPlugin.getDefault().getPreferenceStore());
}
protected Label createDescriptionLabel(Composite parent) {
return null; // no description for new look.
}
/*
* @see org.eclipse.ui.internal.editors.text.AbstractConfigureationBlockPreferencePage#createConfigurationBlock(org.eclipse.ui.internal.editors.text.OverlayPreferenceStore)
*/
protected IPreferenceConfigurationBlock createConfigurationBlock(OverlayPreferenceStore overlayPreferenceStore) {
return new SmartTypingConfigurationBlock(overlayPreferenceStore);
}
}

View file

@ -0,0 +1,194 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences.formatter;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.SWT;
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.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.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.StatusDialog;
import org.eclipse.cdt.internal.ui.util.Messages;
import org.eclipse.cdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.cdt.internal.ui.preferences.formatter.ProfileManager.CustomProfile;
/**
* The dialog to rename an imported profile.
*/
public class AlreadyExistsDialog extends StatusDialog {
private Composite fComposite;
protected Text fNameText;
private Button fRenameRadio, fOverwriteRadio;
private final int NUM_COLUMNS= 2;
private final StatusInfo fOk;
private final StatusInfo fEmpty;
private final StatusInfo fDuplicate;
private final CustomProfile fProfile;
private final ProfileManager fProfileManager;
public AlreadyExistsDialog(Shell parentShell, CustomProfile profile, ProfileManager profileManager) {
super(parentShell);
fProfile= profile;
fProfileManager= profileManager;
fOk= new StatusInfo();
fDuplicate= new StatusInfo(IStatus.ERROR, FormatterMessages.AlreadyExistsDialog_message_profile_already_exists);
fEmpty= new StatusInfo(IStatus.ERROR, FormatterMessages.AlreadyExistsDialog_message_profile_name_empty);
}
public void create() {
super.create();
setTitle(FormatterMessages.AlreadyExistsDialog_dialog_title);
}
public Control createDialogArea(Composite parent) {
initializeComposite(parent);
createLabel(Messages.format(FormatterMessages.AlreadyExistsDialog_dialog_label, fProfile.getName()));
fRenameRadio= createRadioButton(FormatterMessages.AlreadyExistsDialog_rename_radio_button_desc);
fNameText= createTextField();
fOverwriteRadio= createRadioButton(FormatterMessages.AlreadyExistsDialog_overwrite_radio_button_desc);
fRenameRadio.setSelection(true);
fNameText.setText(fProfile.getName());
fNameText.setSelection(0, fProfile.getName().length());
fNameText.setFocus();
fNameText.addModifyListener( new ModifyListener() {
public void modifyText(ModifyEvent e) {
doValidation();
}
});
fRenameRadio.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
fNameText.setEnabled(true);
fNameText.setFocus();
fNameText.setSelection(0, fNameText.getText().length());
doValidation();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
fOverwriteRadio.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
fNameText.setEnabled(false);
doValidation();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
updateStatus(fDuplicate);
applyDialogFont(fComposite);
return fComposite;
}
private void initializeComposite(Composite parent) {
fComposite= new Composite(parent, SWT.NULL);
final GridLayout layout= new GridLayout();
layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
layout.marginWidth= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
layout.verticalSpacing= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
layout.numColumns= NUM_COLUMNS;
fComposite.setLayout(layout);
}
private Label createLabel(String text) {
final GridData gd= new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan= NUM_COLUMNS;
gd.widthHint= convertWidthInCharsToPixels(60);
final Label label= new Label(fComposite, SWT.WRAP);
label.setText(text);
label.setLayoutData(gd);
return label;
}
private Button createRadioButton(String text) {
final GridData gd = new GridData();
gd.horizontalSpan = NUM_COLUMNS;
gd.widthHint= convertWidthInCharsToPixels(60);
final Button radio= new Button(fComposite, SWT.RADIO);
radio.setLayoutData(gd);
radio.setText(text);
return radio;
}
private Text createTextField() {
final GridData gd = new GridData( GridData.FILL_HORIZONTAL);
gd.horizontalSpan= NUM_COLUMNS;
final Text text= new Text(fComposite, SWT.SINGLE | SWT.BORDER);
text.setLayoutData(gd);
return text;
}
/**
* Validate the current settings
*/
protected void doValidation() {
if (fOverwriteRadio.getSelection()) {
updateStatus(fOk);
return;
}
final String name= fNameText.getText().trim();
if (name.length() == 0) {
updateStatus(fEmpty);
return;
}
if (fProfileManager.containsName(name)) {
updateStatus(fDuplicate);
return;
}
updateStatus(fOk);
}
protected void okPressed() {
if (!getStatus().isOK())
return;
if (fRenameRadio.getSelection())
fProfile.rename(fNameText.getText().trim(), fProfileManager);
super.okPressed();
}
}

View file

@ -0,0 +1,198 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences.formatter;
import java.util.Map;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.preference.PreferenceStore;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.MarginPainter;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants;
import org.eclipse.ui.texteditor.ChainedPreferenceStore;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.cdt.ui.PreferenceConstants;
import org.eclipse.cdt.ui.text.ICPartitions;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.ui.editor.CSourceViewer;
import org.eclipse.cdt.internal.ui.text.CSourceViewerConfiguration;
import org.eclipse.cdt.internal.ui.text.CTextTools;
import org.eclipse.cdt.internal.ui.text.SimpleCSourceViewerConfiguration;
public abstract class CPreview {
private final class CSourcePreviewerUpdater {
final IPropertyChangeListener fontListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(PreferenceConstants.EDITOR_TEXT_FONT)) {
final Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT);
fSourceViewer.getTextWidget().setFont(font);
if (fMarginPainter != null) {
fMarginPainter.initialize();
}
}
}
};
final IPropertyChangeListener propertyListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
if (fViewerConfiguration.affectsTextPresentation(event)) {
fViewerConfiguration.handlePropertyChangeEvent(event);
fSourceViewer.invalidateTextPresentation();
}
}
};
public CSourcePreviewerUpdater() {
JFaceResources.getFontRegistry().addListener(fontListener);
fPreferenceStore.addPropertyChangeListener(propertyListener);
fSourceViewer.getTextWidget().addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
JFaceResources.getFontRegistry().removeListener(fontListener);
fPreferenceStore.removePropertyChangeListener(propertyListener);
}
});
}
}
protected final CSourceViewerConfiguration fViewerConfiguration;
protected final Document fPreviewDocument;
protected final SourceViewer fSourceViewer;
protected final IPreferenceStore fPreferenceStore;
protected final MarginPainter fMarginPainter;
protected Map fWorkingValues;
private int fTabSize= 0;
/**
* Create a new C preview
* @param workingValues
* @param parent
*/
public CPreview(Map workingValues, Composite parent) {
CTextTools tools= CUIPlugin.getDefault().getTextTools();
fPreviewDocument= new Document();
fWorkingValues= workingValues;
tools.setupCDocumentPartitioner( fPreviewDocument, ICPartitions.C_PARTITIONING);
PreferenceStore prioritizedSettings= new PreferenceStore();
IPreferenceStore[] chain= { prioritizedSettings, CUIPlugin.getDefault().getCombinedPreferenceStore() };
fPreferenceStore= new ChainedPreferenceStore(chain);
fSourceViewer= new CSourceViewer(parent, null, null, false, SWT.READ_ONLY | SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER);
fViewerConfiguration= new SimpleCSourceViewerConfiguration(tools.getColorManager(), fPreferenceStore, null, ICPartitions.C_PARTITIONING, true);
fSourceViewer.configure(fViewerConfiguration);
fSourceViewer.getTextWidget().setFont(JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT));
fMarginPainter= new MarginPainter(fSourceViewer);
final RGB rgb= PreferenceConverter.getColor(fPreferenceStore, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLOR);
fMarginPainter.setMarginRulerColor(tools.getColorManager().getColor(rgb));
fSourceViewer.addPainter(fMarginPainter);
new CSourcePreviewerUpdater();
fSourceViewer.setDocument(fPreviewDocument);
}
public Control getControl() {
return fSourceViewer.getControl();
}
public void update() {
if (fWorkingValues == null) {
fPreviewDocument.set(""); //$NON-NLS-1$
return;
}
// update the print margin
final String value= (String)fWorkingValues.get(DefaultCodeFormatterConstants.FORMATTER_LINE_SPLIT);
final int lineWidth= getPositiveIntValue(value, 0);
fMarginPainter.setMarginRulerColumn(lineWidth);
// update the tab size
final int tabSize= getPositiveIntValue((String) fWorkingValues.get(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE), 0);
if (tabSize != fTabSize) fSourceViewer.getTextWidget().setTabs(tabSize);
fTabSize= tabSize;
final StyledText widget= (StyledText)fSourceViewer.getControl();
final int height= widget.getClientArea().height;
final int top0= widget.getTopPixel();
final int totalPixels0= getHeightOfAllLines(widget);
final int topPixelRange0= totalPixels0 > height ? totalPixels0 - height : 0;
widget.setRedraw(false);
doFormatPreview();
fSourceViewer.setSelection(null);
final int totalPixels1= getHeightOfAllLines(widget);
final int topPixelRange1= totalPixels1 > height ? totalPixels1 - height : 0;
final int top1= topPixelRange0 > 0 ? (int)(topPixelRange1 * top0 / (double)topPixelRange0) : 0;
widget.setTopPixel(top1);
widget.setRedraw(true);
}
private int getHeightOfAllLines(StyledText styledText) {
int height= 0;
int lineCount= styledText.getLineCount();
for (int i= 0; i < lineCount; i++)
height= height + styledText.getLineHeight(styledText.getOffsetAtLine(i));
return height;
}
protected abstract void doFormatPreview();
private static int getPositiveIntValue(String string, int defaultValue) {
try {
int i= Integer.parseInt(string);
if (i >= 0) {
return i;
}
} catch (NumberFormatException e) {
}
return defaultValue;
}
public final Map getWorkingValues() {
return fWorkingValues;
}
public final void setWorkingValues(Map workingValues) {
fWorkingValues= workingValues;
}
}

View file

@ -0,0 +1,548 @@
/*******************************************************************************
* Copyright (c) 2000, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Aaron Luchko, aluchko@redhat.com - 105926 [Formatter] Exporting Unnamed profile fails silently
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences.formatter;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.preferences.DefaultScope;
import org.eclipse.core.runtime.preferences.IScopeContext;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ProjectScope;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
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.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.internal.ui.util.Messages;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.ui.preferences.PreferencesAccess;
import org.eclipse.cdt.internal.ui.preferences.formatter.ProfileManager.CustomProfile;
import org.eclipse.cdt.internal.ui.preferences.formatter.ProfileManager.Profile;
import org.eclipse.cdt.internal.ui.util.ExceptionHandler;
import org.eclipse.cdt.internal.ui.util.PixelConverter;
import org.eclipse.cdt.internal.ui.util.SWTUtil;
import org.osgi.service.prefs.BackingStoreException;
/**
* The code formatter preference page.
*/
public class CodeFormatterConfigurationBlock {
private static final String DIALOGSTORE_LASTLOADPATH= CUIPlugin.PLUGIN_ID + ".codeformatter.loadpath"; //$NON-NLS-1$
private static final String DIALOGSTORE_LASTSAVEPATH= CUIPlugin.PLUGIN_ID + ".codeformatter.savepath"; //$NON-NLS-1$
private class StoreUpdater implements Observer {
public StoreUpdater() {
fProfileManager.addObserver(this);
}
public void update(Observable o, Object arg) {
final int value= ((Integer)arg).intValue();
switch (value) {
case ProfileManager.PROFILE_DELETED_EVENT:
case ProfileManager.PROFILE_RENAMED_EVENT:
case ProfileManager.PROFILE_CREATED_EVENT:
case ProfileManager.SETTINGS_CHANGED_EVENT:
try {
ProfileStore.writeProfiles(fProfileManager.getSortedProfiles(), fInstanceScope); // update profile store
fProfileManager.commitChanges(fCurrContext); // update formatter settings with curently selected profile
} catch (CoreException x) {
CUIPlugin.getDefault().log(x);
}
break;
case ProfileManager.SELECTION_CHANGED_EVENT:
fProfileManager.commitChanges(fCurrContext); // update formatter settings with curently selected profile
break;
}
}
}
private class ProfileComboController implements Observer, SelectionListener {
private final List fSortedProfiles;
public ProfileComboController() {
fSortedProfiles= fProfileManager.getSortedProfiles();
fProfileCombo.addSelectionListener(this);
fProfileManager.addObserver(this);
updateProfiles();
updateSelection();
}
public void widgetSelected(SelectionEvent e) {
final int index= fProfileCombo.getSelectionIndex();
fProfileManager.setSelected((Profile)fSortedProfiles.get(index));
}
public void widgetDefaultSelected(SelectionEvent e) {}
public void update(Observable o, Object arg) {
if (arg == null) return;
final int value= ((Integer)arg).intValue();
switch (value) {
case ProfileManager.PROFILE_CREATED_EVENT:
case ProfileManager.PROFILE_DELETED_EVENT:
case ProfileManager.PROFILE_RENAMED_EVENT:
updateProfiles();
updateSelection();
break;
case ProfileManager.SELECTION_CHANGED_EVENT:
updateSelection();
break;
}
}
private void updateProfiles() {
fProfileCombo.setItems(fProfileManager.getSortedDisplayNames());
}
private void updateSelection() {
fProfileCombo.setText(fProfileManager.getSelected().getName());
}
}
private class ButtonController implements Observer, SelectionListener {
public ButtonController() {
fProfileManager.addObserver(this);
fNewButton.addSelectionListener(this);
fRenameButton.addSelectionListener(this);
fEditButton.addSelectionListener(this);
fDeleteButton.addSelectionListener(this);
fSaveButton.addSelectionListener(this);
fLoadButton.addSelectionListener(this);
update(fProfileManager, null);
}
public void update(Observable o, Object arg) {
Profile selected= ((ProfileManager)o).getSelected();
final boolean notBuiltIn= !selected.isBuiltInProfile();
fEditButton.setText(notBuiltIn ? FormatterMessages.CodingStyleConfigurationBlock_edit_button_desc
: FormatterMessages.CodingStyleConfigurationBlock_show_button_desc);
fDeleteButton.setEnabled(notBuiltIn);
fSaveButton.setEnabled(notBuiltIn);
fRenameButton.setEnabled(notBuiltIn);
}
public void widgetSelected(SelectionEvent e) {
final Button button= (Button)e.widget;
if (button == fSaveButton)
saveButtonPressed();
else if (button == fEditButton)
modifyButtonPressed();
else if (button == fDeleteButton)
deleteButtonPressed();
else if (button == fNewButton)
newButtonPressed();
else if (button == fLoadButton)
loadButtonPressed();
else if (button == fRenameButton)
renameButtonPressed();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
private void renameButtonPressed() {
if (fProfileManager.getSelected().isBuiltInProfile())
return;
final CustomProfile profile= (CustomProfile) fProfileManager.getSelected();
final RenameProfileDialog renameDialog= new RenameProfileDialog(fComposite.getShell(), profile, fProfileManager);
if (renameDialog.open() == Window.OK) {
fProfileManager.setSelected(renameDialog.getRenamedProfile());
}
}
private void modifyButtonPressed() {
final ModifyDialog modifyDialog= new ModifyDialog(fComposite.getShell(), fProfileManager.getSelected(), fProfileManager, false);
modifyDialog.open();
}
private void deleteButtonPressed() {
if (MessageDialog.openQuestion(
fComposite.getShell(),
FormatterMessages.CodingStyleConfigurationBlock_delete_confirmation_title,
Messages.format(FormatterMessages.CodingStyleConfigurationBlock_delete_confirmation_question, fProfileManager.getSelected().getName()))) {
fProfileManager.deleteSelected();
}
}
private void newButtonPressed() {
final CreateProfileDialog p= new CreateProfileDialog(fComposite.getShell(), fProfileManager);
if (p.open() != Window.OK)
return;
if (!p.openEditDialog())
return;
final ModifyDialog modifyDialog= new ModifyDialog(fComposite.getShell(), p.getCreatedProfile(), fProfileManager, true);
modifyDialog.open();
}
private void saveButtonPressed() {
Profile selected= fProfileManager.getSelected();
if (selected.isSharedProfile()) {
final RenameProfileDialog renameDialog= new RenameProfileDialog(fComposite.getShell(), selected, fProfileManager);
if (renameDialog.open() != Window.OK) {
return;
}
selected= renameDialog.getRenamedProfile();
fProfileManager.setSelected(selected);
}
final FileDialog dialog= new FileDialog(fComposite.getShell(), SWT.SAVE);
dialog.setText(FormatterMessages.CodingStyleConfigurationBlock_save_profile_dialog_title);
dialog.setFilterExtensions(new String [] {"*.xml"}); //$NON-NLS-1$
final String lastPath= CUIPlugin.getDefault().getDialogSettings().get(DIALOGSTORE_LASTSAVEPATH);
if (lastPath != null) {
dialog.setFilterPath(lastPath);
}
final String path= dialog.open();
if (path == null)
return;
CUIPlugin.getDefault().getDialogSettings().put(DIALOGSTORE_LASTSAVEPATH, dialog.getFilterPath());
final File file= new File(path);
if (file.exists() && !MessageDialog.openQuestion(fComposite.getShell(), FormatterMessages.CodingStyleConfigurationBlock_save_profile_overwrite_title, Messages.format(FormatterMessages.CodingStyleConfigurationBlock_save_profile_overwrite_message, path))) {
return;
}
final Collection profiles= new ArrayList();
profiles.add(selected);
try {
ProfileStore.writeProfilesToFile(profiles, file);
} catch (CoreException e) {
final String title= FormatterMessages.CodingStyleConfigurationBlock_save_profile_error_title;
final String message= FormatterMessages.CodingStyleConfigurationBlock_save_profile_error_message;
ExceptionHandler.handle(e, fComposite.getShell(), title, message);
}
}
private void loadButtonPressed() {
final FileDialog dialog= new FileDialog(fComposite.getShell(), SWT.OPEN);
dialog.setText(FormatterMessages.CodingStyleConfigurationBlock_load_profile_dialog_title);
dialog.setFilterExtensions(new String [] {"*.xml"}); //$NON-NLS-1$
final String lastPath= CUIPlugin.getDefault().getDialogSettings().get(DIALOGSTORE_LASTLOADPATH);
if (lastPath != null) {
dialog.setFilterPath(lastPath);
}
final String path= dialog.open();
if (path == null)
return;
CUIPlugin.getDefault().getDialogSettings().put(DIALOGSTORE_LASTLOADPATH, dialog.getFilterPath());
final File file= new File(path);
Collection profiles= null;
try {
profiles= ProfileStore.readProfilesFromFile(file);
} catch (CoreException e) {
final String title= FormatterMessages.CodingStyleConfigurationBlock_load_profile_error_title;
final String message= FormatterMessages.CodingStyleConfigurationBlock_load_profile_error_message;
ExceptionHandler.handle(e, fComposite.getShell(), title, message);
}
if (profiles == null || profiles.isEmpty())
return;
final CustomProfile profile= (CustomProfile)profiles.iterator().next();
if (ProfileVersioner.getVersionStatus(profile) > 0) {
final String title= FormatterMessages.CodingStyleConfigurationBlock_load_profile_error_too_new_title;
final String message= FormatterMessages.CodingStyleConfigurationBlock_load_profile_error_too_new_message;
MessageDialog.openWarning(fComposite.getShell(), title, message);
}
if (fProfileManager.containsName(profile.getName())) {
final AlreadyExistsDialog aeDialog= new AlreadyExistsDialog(fComposite.getShell(), profile, fProfileManager);
if (aeDialog.open() != Window.OK)
return;
}
ProfileVersioner.updateAndComplete(profile);
fProfileManager.addProfile(profile);
}
}
// private class PreviewController implements Observer {
//
// public PreviewController() {
// fProfileManager.addObserver(this);
// fCodeStylePreview.setWorkingValues(fProfileManager.getSelected().getSettings());
// fCodeStylePreview.update();
// }
//
// public void update(Observable o, Object arg) {
// final int value= ((Integer)arg).intValue();
// switch (value) {
// case ProfileManager.PROFILE_CREATED_EVENT:
// case ProfileManager.PROFILE_DELETED_EVENT:
// case ProfileManager.SELECTION_CHANGED_EVENT:
// case ProfileManager.SETTINGS_CHANGED_EVENT:
// fCodeStylePreview.setWorkingValues(((ProfileManager)o).getSelected().getSettings());
// fCodeStylePreview.update();
// }
// }
// }
// /**
// * Some C source code used for preview.
// */
// private final static String PREVIEW=
// "/*\n* " + //$NON-NLS-1$
// FormatterMessages.CodingStyleConfigurationBlock_preview_title +
// "\n*/\n\n" + //$NON-NLS-1$
// "#include <math.h>\n" + //$NON-NLS-1$
// "class Point {" + //$NON-NLS-1$
// "public:" + //$NON-NLS-1$
// "Point(double xc, double yc) : x(xc), y(yc) {}" + //$NON-NLS-1$
// "double distance(const Point& other) const;" + //$NON-NLS-1$
// "double x;" + //$NON-NLS-1$
// "double y;" + //$NON-NLS-1$
// "};" + //$NON-NLS-1$
// "float Point::distance(const Point& other) const {" + //$NON-NLS-1$
// "double dx = x - other.x;" + //$NON-NLS-1$
// "double dy = y - other.y;" + //$NON-NLS-1$
// "return sqrt(dx * dx + dy * dy);" + //$NON-NLS-1$
// "}"; //$NON-NLS-1$
/**
* The GUI controls
*/
protected Composite fComposite;
protected Combo fProfileCombo;
protected Button fEditButton;
protected Button fRenameButton;
protected Button fDeleteButton;
protected Button fNewButton;
protected Button fLoadButton;
protected Button fSaveButton;
/**
* The ProfileManager, the model of this page.
*/
protected final ProfileManager fProfileManager;
private CustomCodeFormatterBlock fCustomCodeFormatterBlock;
/**
* The CPreview.
*/
// protected TranslationUnitPreview fCodeStylePreview;
private PixelConverter fPixConv;
private IScopeContext fCurrContext;
private IScopeContext fInstanceScope;
/**
* Create a new <code>CodeFormatterConfigurationBlock</code>.
*/
public CodeFormatterConfigurationBlock(IProject project, PreferencesAccess access) {
fInstanceScope= access.getInstanceScope();
List profiles= null;
try {
profiles= ProfileStore.readProfiles(fInstanceScope);
} catch (CoreException e) {
CUIPlugin.getDefault().log(e);
}
if (profiles == null) {
try {
// bug 129427
profiles= ProfileStore.readProfilesFromPreferences(new DefaultScope());
} catch (CoreException e) {
CUIPlugin.getDefault().log(e);
}
}
if (profiles == null)
profiles= new ArrayList();
if (project != null) {
fCurrContext= access.getProjectScope(project);
} else {
fCurrContext= fInstanceScope;
}
fProfileManager= new ProfileManager(profiles, fCurrContext, access);
fCustomCodeFormatterBlock= new CustomCodeFormatterBlock(CUIPlugin.getDefault().getPluginPreferences());
new StoreUpdater();
}
/**
* Create the contents
* @param parent Parent composite
* @return Created control
*/
public Composite createContents(Composite parent) {
final int numColumns = 5;
fPixConv = new PixelConverter(parent);
fComposite = createComposite(parent, numColumns);
fProfileCombo= createProfileCombo(fComposite, numColumns - 3, fPixConv.convertWidthInCharsToPixels(20));
fEditButton= createButton(fComposite, FormatterMessages.CodingStyleConfigurationBlock_edit_button_desc, GridData.HORIZONTAL_ALIGN_BEGINNING);
fRenameButton= createButton(fComposite, FormatterMessages.CodingStyleConfigurationBlock_rename_button_desc, GridData.HORIZONTAL_ALIGN_BEGINNING);
fDeleteButton= createButton(fComposite, FormatterMessages.CodingStyleConfigurationBlock_remove_button_desc, GridData.HORIZONTAL_ALIGN_BEGINNING);
final Composite group= createComposite(fComposite, 4);
final GridData groupData= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
groupData.horizontalSpan= numColumns;
group.setLayoutData(groupData);
fNewButton= createButton(group, FormatterMessages.CodingStyleConfigurationBlock_new_button_desc, GridData.HORIZONTAL_ALIGN_BEGINNING);
((GridData)createLabel(group, "", 1).getLayoutData()).grabExcessHorizontalSpace= true; //$NON-NLS-1$
fLoadButton= createButton(group, FormatterMessages.CodingStyleConfigurationBlock_load_button_desc, GridData.HORIZONTAL_ALIGN_END);
fSaveButton= createButton(group, FormatterMessages.CodingStyleConfigurationBlock_save_button_desc, GridData.HORIZONTAL_ALIGN_END);
fCustomCodeFormatterBlock.createContents(fComposite);
// createLabel(fComposite, FormatterMessages.CodingStyleConfigurationBlock_preview_label_text, numColumns);
// configurePreview(fComposite, numColumns);
new ButtonController();
new ProfileComboController();
// new PreviewController();
return fComposite;
}
private static Button createButton(Composite composite, String text, final int style) {
final Button button= new Button(composite, SWT.PUSH);
button.setFont(composite.getFont());
button.setText(text);
final GridData gd= new GridData(style);
gd.widthHint= SWTUtil.getButtonWidthHint(button);
button.setLayoutData(gd);
return button;
}
private static Combo createProfileCombo(Composite composite, int span, int widthHint) {
final GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = span;
gd.widthHint= widthHint;
final Combo combo= new Combo(composite, SWT.DROP_DOWN | SWT.READ_ONLY);
combo.setFont(composite.getFont());
combo.setLayoutData(gd);
return combo;
}
private Label createLabel(Composite composite, String text, int numColumns) {
final GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan = numColumns;
gd.widthHint= 0;
final Label label = new Label(composite, SWT.WRAP);
label.setFont(composite.getFont());
label.setText(text);
label.setLayoutData(gd);
return label;
}
private Composite createComposite(Composite parent, int numColumns) {
final Composite composite = new Composite(parent, SWT.NONE);
composite.setFont(parent.getFont());
final GridLayout layout = new GridLayout(numColumns, false);
layout.marginHeight = 0;
layout.marginWidth = 0;
composite.setLayout(layout);
return composite;
}
// private void configurePreview(Composite composite, int numColumns) {
// fCodeStylePreview= new TranslationUnitPreview(fProfileManager.getSelected().getSettings(), composite);
// fCodeStylePreview.setPreviewText(PREVIEW);
//
// final GridData gd = new GridData(GridData.FILL_VERTICAL | GridData.HORIZONTAL_ALIGN_FILL);
// gd.horizontalSpan = numColumns;
// gd.verticalSpan= 7;
// gd.widthHint = 0;
// gd.heightHint = 0;
// fCodeStylePreview.getControl().setLayoutData(gd);
// }
public final boolean hasProjectSpecificOptions(IProject project) {
if (project != null) {
return ProfileManager.hasProjectSpecificSettings(new ProjectScope(project));
}
return false;
}
public boolean performOk() {
fCustomCodeFormatterBlock.performOk();
return true;
}
public void performApply() {
try {
fCurrContext.getNode(CUIPlugin.PLUGIN_ID).flush();
fCurrContext.getNode(CCorePlugin.PLUGIN_ID).flush();
if (fCurrContext != fInstanceScope) {
fInstanceScope.getNode(CUIPlugin.PLUGIN_ID).flush();
fInstanceScope.getNode(CCorePlugin.PLUGIN_ID).flush();
}
fCustomCodeFormatterBlock.performOk();
} catch (BackingStoreException e) {
CUIPlugin.getDefault().log(e);
}
}
public void performDefaults() {
Profile profile= fProfileManager.getProfile(ProfileManager.DEFAULT_PROFILE);
if (profile != null) {
int defaultIndex= fProfileManager.getSortedProfiles().indexOf(profile);
if (defaultIndex != -1) {
fProfileManager.setSelected(profile);
}
}
fCustomCodeFormatterBlock.performDefaults();
}
public void dispose() {
}
public void enableProjectSpecificSettings(boolean useProjectSpecificSettings) {
if (useProjectSpecificSettings) {
fProfileManager.commitChanges(fCurrContext);
} else {
fProfileManager.clearAllSettings(fCurrContext);
}
}
}

View file

@ -0,0 +1,197 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences.formatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.SWT;
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.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.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.StatusDialog;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.cdt.internal.ui.preferences.formatter.ProfileManager.CustomProfile;
import org.eclipse.cdt.internal.ui.preferences.formatter.ProfileManager.Profile;
/**
* The dialog to create a new profile.
*/
public class CreateProfileDialog extends StatusDialog {
private static final String PREF_OPEN_EDIT_DIALOG= CUIPlugin.PLUGIN_ID + ".codeformatter.create_profile_dialog.open_edit"; //$NON-NLS-1$
private Text fNameText;
private Combo fProfileCombo;
private Button fEditCheckbox;
private final static StatusInfo fOk= new StatusInfo();
private final static StatusInfo fEmpty= new StatusInfo(IStatus.ERROR, FormatterMessages.CreateProfileDialog_status_message_profile_name_is_empty);
private final static StatusInfo fDuplicate= new StatusInfo(IStatus.ERROR, FormatterMessages.CreateProfileDialog_status_message_profile_with_this_name_already_exists);
private final ProfileManager fProfileManager;
private final List fSortedProfiles;
private final String [] fSortedNames;
private CustomProfile fCreatedProfile;
protected boolean fOpenEditDialog;
public CreateProfileDialog(Shell parentShell, ProfileManager profileManager) {
super(parentShell);
fProfileManager= profileManager;
fSortedProfiles= fProfileManager.getSortedProfiles();
fSortedNames= fProfileManager.getSortedDisplayNames();
}
public void create() {
super.create();
setTitle(FormatterMessages.CreateProfileDialog_dialog_title);
}
public Control createDialogArea(Composite parent) {
final int numColumns= 2;
GridData gd;
final GridLayout layout= new GridLayout(numColumns, false);
layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
layout.marginWidth= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
layout.verticalSpacing= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
final Composite composite= new Composite(parent, SWT.NONE);
composite.setLayout(layout);
// Create "Profile name:" label
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = numColumns;
gd.widthHint= convertWidthInCharsToPixels(60);
final Label nameLabel = new Label(composite, SWT.WRAP);
nameLabel.setText(FormatterMessages.CreateProfileDialog_profile_name_label_text);
nameLabel.setLayoutData(gd);
// Create text field to enter name
gd = new GridData( GridData.FILL_HORIZONTAL);
gd.horizontalSpan= numColumns;
fNameText= new Text(composite, SWT.SINGLE | SWT.BORDER);
fNameText.setLayoutData(gd);
fNameText.addModifyListener( new ModifyListener() {
public void modifyText(ModifyEvent e) {
doValidation();
}
});
// Create "Initialize settings ..." label
gd = new GridData();
gd.horizontalSpan = numColumns;
Label profileLabel = new Label(composite, SWT.WRAP);
profileLabel.setText(FormatterMessages.CreateProfileDialog_base_profile_label_text);
profileLabel.setLayoutData(gd);
gd= new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan= numColumns;
fProfileCombo = new Combo(composite, SWT.DROP_DOWN | SWT.READ_ONLY);
fProfileCombo.setLayoutData(gd);
// "Open the edit dialog now" checkbox
gd= new GridData();
gd.horizontalSpan= numColumns;
fEditCheckbox= new Button(composite, SWT.CHECK);
fEditCheckbox.setText(FormatterMessages.CreateProfileDialog_open_edit_dialog_checkbox_text);
fEditCheckbox.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
fOpenEditDialog= ((Button)e.widget).getSelection();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
final IDialogSettings dialogSettings= CUIPlugin.getDefault().getDialogSettings();//.get(PREF_OPEN_EDIT_DIALOG);
if (dialogSettings.get(PREF_OPEN_EDIT_DIALOG) != null) {
fOpenEditDialog= dialogSettings.getBoolean(PREF_OPEN_EDIT_DIALOG);
} else {
fOpenEditDialog= true;
}
fEditCheckbox.setSelection(fOpenEditDialog);
fProfileCombo.setItems(fSortedNames);
fProfileCombo.setText(fProfileManager.getProfile(ProfileManager.DEFAULT_PROFILE).getName());
updateStatus(fEmpty);
applyDialogFont(composite);
fNameText.setFocus();
return composite;
}
/**
* Validate the current settings
*/
protected void doValidation() {
final String name= fNameText.getText().trim();
if (fProfileManager.containsName(name)) {
updateStatus(fDuplicate);
return;
}
if (name.length() == 0) {
updateStatus(fEmpty);
return;
}
updateStatus(fOk);
}
protected void okPressed() {
if (!getStatus().isOK())
return;
CUIPlugin.getDefault().getDialogSettings().put(PREF_OPEN_EDIT_DIALOG, fOpenEditDialog);
final Map baseSettings= new HashMap(((Profile)fSortedProfiles.get(fProfileCombo.getSelectionIndex())).getSettings());
final String profileName= fNameText.getText();
fCreatedProfile= new CustomProfile(profileName, baseSettings, ProfileVersioner.CURRENT_VERSION);
fProfileManager.addProfile(fCreatedProfile);
super.okPressed();
}
public final CustomProfile getCreatedProfile() {
return fCreatedProfile;
}
public final boolean openEditDialog() {
return fOpenEditDialog;
}
}

View file

@ -7,9 +7,10 @@
*
* Contributors:
* QNX Software Systems - Initial API and implementation
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.ui.dialogs;
package org.eclipse.cdt.internal.ui.preferences.formatter;
import java.util.HashMap;
import java.util.Iterator;
@ -36,12 +37,11 @@ import org.eclipse.cdt.core.CCorePreferenceConstants;
import org.eclipse.cdt.utils.ui.controls.ControlFactory;
import org.eclipse.cdt.internal.ui.ICHelpContextIds;
import org.eclipse.cdt.internal.ui.preferences.PreferencesMessages;
/**
*
*/
public class CodeFormatterBlock {
public class CustomCodeFormatterBlock {
private HashMap idMap = new HashMap();
Preferences fPrefs;
@ -50,10 +50,10 @@ public class CodeFormatterBlock {
private static final String ATTR_ID = "id"; //$NON-NLS-1$
// This is a hack until we have a default Formatter.
// For now it is comment out in the plugin.xml
private static final String NONE=PreferencesMessages.CodeFormatterPreferencePage_emptyName;
private static final String NONE = FormatterMessages.CustomCodeFormatterBlock_no_formatter;
public CodeFormatterBlock(Preferences prefs) {
public CustomCodeFormatterBlock(Preferences prefs) {
fPrefs = prefs;
initializeFormatters();
}
@ -96,21 +96,19 @@ public class CodeFormatterBlock {
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
*/
public Control createControl(Composite parent) {
Composite control = ControlFactory.createComposite(parent, 2);
((GridLayout) control.getLayout()).makeColumnsEqualWidth = false;
((GridLayout) control.getLayout()).marginWidth = 5;
public Control createContents(Composite parent) {
Composite composite = ControlFactory.createComposite(parent, 1);
((GridLayout)composite.getLayout()).marginWidth = 0;
((GridData)composite.getLayoutData()).horizontalSpan = 2;
PlatformUI.getWorkbench().getHelpSystem().setHelp(control, ICHelpContextIds.CODEFORMATTER_PREFERENCE_PAGE);
PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, ICHelpContextIds.CODEFORMATTER_PREFERENCE_PAGE);
ControlFactory.createEmptySpace(control, 2);
ControlFactory.createEmptySpace(composite, 1);
Label label = ControlFactory.createLabel(control, PreferencesMessages.CodeFormatterPreferencePage_selectionName);
label.setLayoutData(new GridData());
fFormatterCombo = new Combo(control, SWT.DROP_DOWN | SWT.READ_ONLY);
GridData gd = new GridData(GridData.GRAB_HORIZONTAL);
gd.grabExcessHorizontalSpace = true;
fFormatterCombo.setLayoutData(gd);
Label label = ControlFactory.createLabel(composite, FormatterMessages.CustomCodeFormatterBlock_formatter_name);
fFormatterCombo = new Combo(composite, SWT.DROP_DOWN | SWT.READ_ONLY);
fFormatterCombo.setFont(parent.getFont());
fFormatterCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
fFormatterCombo.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handleFormatterChanged();
@ -121,16 +119,24 @@ public class CodeFormatterBlock {
fFormatterCombo.add((String) items.next());
}
label = ControlFactory.createLabel(parent, FormatterMessages.CustomCodeFormatterBlock_contributed_formatter_warning);
((GridData)label.getLayoutData()).horizontalSpan = 5;
initDefault();
handleFormatterChanged();
return control;
if (getNumberOfAvailableFormatters() == 0) {
composite.setVisible(false);
label.setVisible(false);
}
return composite;
}
public void handleFormatterChanged() {
private void handleFormatterChanged() {
// TODO: UI part.
}
public void initDefault() {
private void initDefault() {
boolean init = false;
String selection = CCorePlugin.getOption(CCorePreferenceConstants.CODE_FORMATTER);
if (selection != null) {
@ -165,4 +171,7 @@ public class CodeFormatterBlock {
}
}
private final int getNumberOfAvailableFormatters() {
return idMap.size() - 1;
}
}

View file

@ -0,0 +1,461 @@
/*******************************************************************************
* Copyright (c) 2000, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences.formatter;
import org.eclipse.osgi.util.NLS;
/**
* Helper class to get NLSed messages.
*/
final class FormatterMessages extends NLS {
private static final String BUNDLE_NAME= FormatterMessages.class.getName();
private FormatterMessages() {
// Do not instantiate
}
// public static String WhiteSpaceTabPage_assignments;
// public static String WhiteSpaceTabPage_assignments_before_assignment_operator;
// public static String WhiteSpaceTabPage_assignments_after_assignment_operator;
// public static String WhiteSpaceTabPage_operators;
// public static String WhiteSpaceTabPage_operators_before_binary_operators;
// public static String WhiteSpaceTabPage_operators_after_binary_operators;
// public static String WhiteSpaceTabPage_operators_before_unary_operators;
// public static String WhiteSpaceTabPage_operators_after_unary_operators;
// public static String WhiteSpaceTabPage_operators_before_prefix_operators;
// public static String WhiteSpaceTabPage_operators_after_prefix_operators;
// public static String WhiteSpaceTabPage_operators_before_postfix_operators;
// public static String WhiteSpaceTabPage_operators_after_postfix_operators;
// public static String WhiteSpaceTabPage_classes;
// public static String WhiteSpaceTabPage_classes_before_opening_brace_of_a_class;
// public static String WhiteSpaceTabPage_classes_before_opening_brace_of_anon_class;
// public static String WhiteSpaceTabPage_classes_before_comma_implements;
// public static String WhiteSpaceTabPage_classes_after_comma_implements;
// public static String WhiteSpaceTabPage_methods;
// public static String WhiteSpaceTabPage_constructors;
// public static String WhiteSpaceTabPage_fields;
// public static String WhiteSpaceTabPage_fields_before_comma;
// public static String WhiteSpaceTabPage_fields_after_comma;
// public static String WhiteSpaceTabPage_localvars;
// public static String WhiteSpaceTabPage_localvars_before_comma;
// public static String WhiteSpaceTabPage_localvars_after_comma;
// public static String WhiteSpaceTabPage_arrayinit;
// public static String WhiteSpaceTabPage_arraydecls;
// public static String WhiteSpaceTabPage_arrayelem;
// public static String WhiteSpaceTabPage_arrayalloc;
// public static String WhiteSpaceTabPage_calls;
// public static String WhiteSpaceTabPage_calls_before_comma_in_method_args;
// public static String WhiteSpaceTabPage_calls_after_comma_in_method_args;
// public static String WhiteSpaceTabPage_calls_before_comma_in_alloc;
// public static String WhiteSpaceTabPage_calls_after_comma_in_alloc;
// public static String WhiteSpaceTabPage_calls_before_comma_in_qalloc;
// public static String WhiteSpaceTabPage_calls_after_comma_in_qalloc;
// public static String WhiteSpaceTabPage_statements;
// public static String WhiteSpaceTabPage_blocks;
// public static String WhiteSpaceTabPage_switch;
// public static String WhiteSpaceTabPage_switch_before_case_colon;
// public static String WhiteSpaceTabPage_switch_before_default_colon;
// public static String WhiteSpaceTabPage_do;
// public static String WhiteSpaceTabPage_synchronized;
// public static String WhiteSpaceTabPage_try;
// public static String WhiteSpaceTabPage_if;
// public static String WhiteSpaceTabPage_assert;
// public static String WhiteSpaceTabPage_for;
// public static String WhiteSpaceTabPage_for_before_comma_init;
// public static String WhiteSpaceTabPage_for_after_comma_init;
// public static String WhiteSpaceTabPage_for_before_comma_inc;
// public static String WhiteSpaceTabPage_for_after_comma_inc;
// public static String WhiteSpaceTabPage_labels;
// public static String WhiteSpaceTabPage_annotations;
// public static String WhiteSpaceTabPage_annotation_types;
// public static String WhiteSpaceTabPage_enums;
// public static String WhiteSpaceTabPage_wildcardtype;
// public static String WhiteSpaceTabPage_param_type_ref;
// public static String WhiteSpaceTabPage_type_arguments;
// public static String WhiteSpaceTabPage_type_parameters;
// public static String WhiteSpaceTabPage_conditionals;
// public static String WhiteSpaceTabPage_typecasts;
// public static String WhiteSpaceTabPage_parenexpr;
// public static String WhiteSpaceTabPage_declarations;
// public static String WhiteSpaceTabPage_expressions;
// public static String WhiteSpaceTabPage_arrays;
// public static String WhiteSpaceTabPage_parameterized_types;
// public static String WhiteSpaceTabPage_after_opening_brace;
// public static String WhiteSpaceTabPage_after_closing_brace;
// public static String WhiteSpaceTabPage_before_opening_brace;
// public static String WhiteSpaceTabPage_before_closing_brace;
// public static String WhiteSpaceTabPage_between_empty_braces;
// public static String WhiteSpaceTabPage_after_opening_paren;
// public static String WhiteSpaceTabPage_after_closing_paren;
// public static String WhiteSpaceTabPage_before_opening_paren;
// public static String WhiteSpaceTabPage_before_closing_paren;
// public static String WhiteSpaceTabPage_between_empty_parens;
// public static String WhiteSpaceTabPage_after_opening_bracket;
// public static String WhiteSpaceTabPage_before_opening_bracket;
// public static String WhiteSpaceTabPage_before_closing_bracket;
// public static String WhiteSpaceTabPage_between_empty_brackets;
// public static String WhiteSpaceTabPage_before_comma_in_params;
// public static String WhiteSpaceTabPage_after_comma_in_params;
// public static String WhiteSpaceTabPage_before_comma_in_throws;
// public static String WhiteSpaceTabPage_after_comma_in_throws;
// public static String WhiteSpaceTabPage_before_ellipsis;
// public static String WhiteSpaceTabPage_after_ellipsis;
// public static String WhiteSpaceTabPage_before_comma;
// public static String WhiteSpaceTabPage_after_comma;
// public static String WhiteSpaceTabPage_after_semicolon;
// public static String WhiteSpaceTabPage_before_semicolon;
// public static String WhiteSpaceTabPage_before_colon;
// public static String WhiteSpaceTabPage_after_colon;
// public static String WhiteSpaceTabPage_before_question;
// public static String WhiteSpaceTabPage_after_question;
// public static String WhiteSpaceTabPage_before_at;
// public static String WhiteSpaceTabPage_after_at;
// public static String WhiteSpaceTabPage_after_opening_angle_bracket;
// public static String WhiteSpaceTabPage_after_closing_angle_bracket;
// public static String WhiteSpaceTabPage_before_opening_angle_bracket;
// public static String WhiteSpaceTabPage_before_closing_angle_bracket;
// public static String WhiteSpaceTabPage_before_and_list;
// public static String WhiteSpaceTabPage_after_and_list;
// public static String WhiteSpaceTabPage_enum_decl_before_opening_brace;
// public static String WhiteSpaceTabPage_enum_decl_before_comma;
// public static String WhiteSpaceTabPage_enum_decl_after_comma;
// public static String WhiteSpaceTabPage_enum_const_arg_before_opening_paren;
// public static String WhiteSpaceTabPage_enum_const_arg_after_opening_paren;
// public static String WhiteSpaceTabPage_enum_const_arg_between_empty_parens;
// public static String WhiteSpaceTabPage_enum_const_arg_before_comma;
// public static String WhiteSpaceTabPage_enum_const_arg_after_comma;
// public static String WhiteSpaceTabPage_enum_const_arg_before_closing_paren;
// public static String WhiteSpaceTabPage_enum_const_before_opening_brace;
// public static String WhiteSpaceTabPage_annot_type_method_before_opening_paren;
// public static String WhiteSpaceTabPage_annot_type_method_between_empty_parens;
// public static String WhiteSpaceTabPage_before_parenthesized_expressions;
// public static String WhiteSpaceTabPage_insert_space;
// public static String WhiteSpaceTabPage_sort_by_c_element;
// public static String WhiteSpaceTabPage_sort_by_syntax_element;
// public static String WhiteSpaceOptions_return;
// public static String WhiteSpaceOptions_before;
// public static String WhiteSpaceOptions_after;
// public static String WhiteSpaceOptions_operator;
// public static String WhiteSpaceOptions_assignment_operator;
// public static String WhiteSpaceOptions_binary_operator;
// public static String WhiteSpaceOptions_unary_operator;
// public static String WhiteSpaceOptions_prefix_operator;
// public static String WhiteSpaceOptions_postfix_operator;
// public static String WhiteSpaceOptions_opening_paren;
// public static String WhiteSpaceOptions_catch;
// public static String WhiteSpaceOptions_for;
// public static String WhiteSpaceOptions_if;
// public static String WhiteSpaceOptions_switch;
// public static String WhiteSpaceOptions_synchronized;
// public static String WhiteSpaceOptions_while;
// public static String WhiteSpaceOptions_assert;
// public static String WhiteSpaceOptions_member_function_declaration;
// public static String WhiteSpaceOptions_constructor;
// public static String WhiteSpaceOptions_method;
// public static String WhiteSpaceOptions_method_call;
// public static String WhiteSpaceOptions_paren_expr;
// public static String WhiteSpaceOptions_enum_constant_body;
// public static String WhiteSpaceOptions_enum_constant_arguments;
// public static String WhiteSpaceOptions_enum_declaration;
// public static String WhiteSpaceOptions_annotation_modifier;
// public static String WhiteSpaceOptions_annotation_modifier_args;
// public static String WhiteSpaceOptions_annotation_type_member;
// public static String WhiteSpaceOptions_annotation_type;
// public static String WhiteSpaceOptions_type_cast;
// public static String WhiteSpaceOptions_parameterized_type;
// public static String WhiteSpaceOptions_type_arguments;
// public static String WhiteSpaceOptions_type_parameters;
// public static String WhiteSpaceOptions_vararg_parameter;
// public static String WhiteSpaceOptions_closing_paren;
// public static String WhiteSpaceOptions_opening_brace;
// public static String WhiteSpaceOptions_closing_brace;
// public static String WhiteSpaceOptions_opening_bracket;
// public static String WhiteSpaceOptions_closing_bracket;
// public static String WhiteSpaceOptions_class_decl;
// public static String WhiteSpaceOptions_anon_class_decl;
// public static String WhiteSpaceOptions_initializer;
// public static String WhiteSpaceOptions_block;
// public static String WhiteSpaceOptions_array_decl;
// public static String WhiteSpaceOptions_array_element_access;
// public static String WhiteSpaceOptions_array_alloc;
// public static String WhiteSpaceOptions_array_init;
// public static String WhiteSpaceOptions_arguments;
// public static String WhiteSpaceOptions_initialization;
// public static String WhiteSpaceOptions_incrementation;
// public static String WhiteSpaceOptions_parameters;
// public static String WhiteSpaceOptions_explicit_constructor_call;
// public static String WhiteSpaceOptions_alloc_expr;
// public static String WhiteSpaceOptions_throws;
// public static String WhiteSpaceOptions_mult_decls;
// public static String WhiteSpaceOptions_local_vars;
// public static String WhiteSpaceOptions_fields;
// public static String WhiteSpaceOptions_implements_clause;
// public static String WhiteSpaceOptions_colon;
// public static String WhiteSpaceOptions_conditional;
// public static String WhiteSpaceOptions_wildcard;
// public static String WhiteSpaceOptions_label;
// public static String WhiteSpaceOptions_comma;
// public static String WhiteSpaceOptions_semicolon;
// public static String WhiteSpaceOptions_question_mark;
// public static String WhiteSpaceOptions_between_empty_parens;
// public static String WhiteSpaceOptions_between_empty_braces;
// public static String WhiteSpaceOptions_between_empty_brackets;
// public static String WhiteSpaceOptions_constructor_decl;
// public static String WhiteSpaceOptions_method_decl;
// public static String WhiteSpaceOptions_case;
// public static String WhiteSpaceOptions_default;
// public static String WhiteSpaceOptions_statements;
// public static String WhiteSpaceOptions_before_opening_paren;
// public static String WhiteSpaceOptions_after_opening_paren;
// public static String WhiteSpaceOptions_before_closing_paren;
// public static String WhiteSpaceOptions_after_closing_paren;
// public static String WhiteSpaceOptions_before_opening_brace;
// public static String WhiteSpaceOptions_after_opening_brace;
// public static String WhiteSpaceOptions_after_closing_brace;
// public static String WhiteSpaceOptions_before_closing_brace;
// public static String WhiteSpaceOptions_before_opening_bracket;
// public static String WhiteSpaceOptions_after_opening_bracket;
// public static String WhiteSpaceOptions_before_closing_bracket;
// public static String WhiteSpaceOptions_before_opening_angle_bracket;
// public static String WhiteSpaceOptions_after_opening_angle_bracket;
// public static String WhiteSpaceOptions_before_closing_angle_bracket;
// public static String WhiteSpaceOptions_after_closing_angle_bracket;
// public static String WhiteSpaceOptions_before_operator;
// public static String WhiteSpaceOptions_after_operator;
// public static String WhiteSpaceOptions_before_comma;
// public static String WhiteSpaceOptions_after_comma;
// public static String WhiteSpaceOptions_after_colon;
// public static String WhiteSpaceOptions_before_colon;
// public static String WhiteSpaceOptions_before_semicolon;
// public static String WhiteSpaceOptions_after_semicolon;
// public static String WhiteSpaceOptions_before_question_mark;
// public static String WhiteSpaceOptions_after_question_mark;
// public static String WhiteSpaceOptions_before_at;
// public static String WhiteSpaceOptions_after_at;
// public static String WhiteSpaceOptions_before_and;
// public static String WhiteSpaceOptions_after_and;
// public static String WhiteSpaceOptions_before_ellipsis;
// public static String WhiteSpaceOptions_after_ellipsis;
// public static String WhiteSpaceOptions_return_with_parenthesized_expression;
// public static String LineWrappingTabPage_compact_if_else;
// public static String LineWrappingTabPage_extends_clause;
// public static String LineWrappingTabPage_enum_constant_arguments;
// public static String LineWrappingTabPage_enum_constants;
// public static String LineWrappingTabPage_implements_clause;
// public static String LineWrappingTabPage_parameters;
// public static String LineWrappingTabPage_arguments;
// public static String LineWrappingTabPage_qualified_invocations;
// public static String LineWrappingTabPage_throws_clause;
// public static String LineWrappingTabPage_object_allocation;
// public static String LineWrappingTabPage_qualified_object_allocation;
// public static String LineWrappingTabPage_array_init;
// public static String LineWrappingTabPage_explicit_constructor_invocations;
// public static String LineWrappingTabPage_conditionals;
// public static String LineWrappingTabPage_binary_exprs;
// public static String LineWrappingTabPage_indentation_default;
// public static String LineWrappingTabPage_indentation_on_column;
// public static String LineWrappingTabPage_indentation_by_one;
// public static String LineWrappingTabPage_class_decls;
// public static String LineWrappingTabPage_method_decls;
// public static String LineWrappingTabPage_constructor_decls;
// public static String LineWrappingTabPage_function_calls;
// public static String LineWrappingTabPage_expressions;
// public static String LineWrappingTabPage_statements;
// public static String LineWrappingTabPage_enum_decls;
// public static String LineWrappingTabPage_wrapping_policy_label_text;
// public static String LineWrappingTabPage_indentation_policy_label_text;
// public static String LineWrappingTabPage_force_split_checkbox_text;
// public static String LineWrappingTabPage_force_split_checkbox_multi_text;
// public static String LineWrappingTabPage_line_width_for_preview_label_text;
// public static String LineWrappingTabPage_group;
// public static String LineWrappingTabPage_multi_group;
// public static String LineWrappingTabPage_multiple_selections;
// public static String LineWrappingTabPage_occurences;
// public static String LineWrappingTabPage_splitting_do_not_split;
// public static String LineWrappingTabPage_splitting_wrap_when_necessary;
// public static String LineWrappingTabPage_splitting_always_wrap_first_others_when_necessary;
// public static String LineWrappingTabPage_splitting_wrap_always;
// public static String LineWrappingTabPage_splitting_wrap_always_indent_all_but_first;
// public static String LineWrappingTabPage_splitting_wrap_always_except_first_only_if_necessary;
// public static String LineWrappingTabPage_width_indent;
// public static String LineWrappingTabPage_width_indent_option_max_line_width;
// public static String LineWrappingTabPage_width_indent_option_default_indent_wrapped;
// public static String LineWrappingTabPage_width_indent_option_default_indent_array;
// public static String LineWrappingTabPage_error_invalid_value;
// public static String LineWrappingTabPage_enum_superinterfaces;
// public static String LineWrappingTabPage_assignment_alignment;
public static String AlreadyExistsDialog_message_profile_already_exists;
public static String AlreadyExistsDialog_message_profile_name_empty;
public static String AlreadyExistsDialog_dialog_title;
public static String AlreadyExistsDialog_dialog_label;
public static String AlreadyExistsDialog_rename_radio_button_desc;
public static String AlreadyExistsDialog_overwrite_radio_button_desc;
// public static String BlankLinesTabPage_preview_header;
// public static String BlankLinesTabPage_compilation_unit_group_title;
// public static String BlankLinesTabPage_compilation_unit_option_before_package;
// public static String BlankLinesTabPage_compilation_unit_option_after_package;
// public static String BlankLinesTabPage_compilation_unit_option_before_import;
// public static String BlankLinesTabPage_compilation_unit_option_after_import;
// public static String BlankLinesTabPage_compilation_unit_option_between_type_declarations;
// public static String BlankLinesTabPage_class_group_title;
// public static String BlankLinesTabPage_class_option_before_first_decl;
// public static String BlankLinesTabPage_class_option_before_decls_of_same_kind;
// public static String BlankLinesTabPage_class_option_before_member_class_decls;
// public static String BlankLinesTabPage_class_option_before_field_decls;
// public static String BlankLinesTabPage_class_option_before_method_decls;
// public static String BlankLinesTabPage_class_option_at_beginning_of_method_body;
// public static String BlankLinesTabPage_blank_lines_group_title;
// public static String BlankLinesTabPage_blank_lines_option_empty_lines_to_preserve;
// public static String BracesTabPage_preview_header;
// public static String BracesTabPage_position_same_line;
// public static String BracesTabPage_position_next_line;
// public static String BracesTabPage_position_next_line_indented;
// public static String BracesTabPage_position_next_line_on_wrap;
// public static String BracesTabPage_group_brace_positions_title;
// public static String BracesTabPage_option_class_declaration;
// public static String BracesTabPage_option_anonymous_class_declaration;
// public static String BracesTabPage_option_method_declaration;
// public static String BracesTabPage_option_constructor_declaration;
// public static String BracesTabPage_option_blocks;
// public static String BracesTabPage_option_blocks_in_case;
// public static String BracesTabPage_option_switch_case;
// public static String BracesTabPage_option_array_initializer;
// public static String BracesTabPage_option_keep_empty_array_initializer_on_one_line;
// public static String BracesTabPage_option_enum_declaration;
// public static String BracesTabPage_option_enumconst_declaration;
// public static String BracesTabPage_option_annotation_type_declaration;
public static String CodingStyleConfigurationBlock_save_profile_dialog_title;
public static String CodingStyleConfigurationBlock_save_profile_error_title;
public static String CodingStyleConfigurationBlock_save_profile_error_message;
public static String CodingStyleConfigurationBlock_load_profile_dialog_title;
public static String CodingStyleConfigurationBlock_load_profile_error_title;
public static String CodingStyleConfigurationBlock_load_profile_error_message;
public static String CodingStyleConfigurationBlock_load_profile_error_too_new_title;
public static String CodingStyleConfigurationBlock_load_profile_error_too_new_message;
public static String CodingStyleConfigurationBlock_preview_title;
public static String CodingStyleConfigurationBlock_save_profile_overwrite_title;
public static String CodingStyleConfigurationBlock_save_profile_overwrite_message;
public static String CodingStyleConfigurationBlock_edit_button_desc;
public static String CodingStyleConfigurationBlock_show_button_desc;
public static String CodingStyleConfigurationBlock_rename_button_desc;
public static String CodingStyleConfigurationBlock_remove_button_desc;
public static String CodingStyleConfigurationBlock_new_button_desc;
public static String CodingStyleConfigurationBlock_load_button_desc;
public static String CodingStyleConfigurationBlock_save_button_desc;
public static String CodingStyleConfigurationBlock_preview_label_text;
public static String CodingStyleConfigurationBlock_error_reading_xml_message;
public static String CodingStyleConfigurationBlock_error_serializing_xml_message;
public static String CodingStyleConfigurationBlock_delete_confirmation_title;
public static String CodingStyleConfigurationBlock_delete_confirmation_question;
public static String CustomCodeFormatterBlock_formatter_name;
public static String CustomCodeFormatterBlock_no_formatter;
public static String CustomCodeFormatterBlock_contributed_formatter_warning;
// public static String CommentsTabPage_group1_title;
// public static String CommentsTabPage_enable_comment_formatting;
// public static String CommentsTabPage_format_header;
// public static String CommentsTabPage_format_html;
// public static String CommentsTabPage_format_code_snippets;
// public static String CommentsTabPage_group2_title;
// public static String CommentsTabPage_clear_blank_lines;
// public static String CommentsTabPage_indent_description_after_param;
// public static String CommentsTabPage_new_line_after_param_tags;
// public static String CommentsTabPage_group3_title;
// public static String CommentsTabPage_line_width;
// public static String ControlStatementsTabPage_preview_header;
// public static String ControlStatementsTabPage_general_group_title;
// public static String ControlStatementsTabPage_general_group_insert_new_line_before_else_statements;
// public static String ControlStatementsTabPage_general_group_insert_new_line_before_catch_statements;
// public static String ControlStatementsTabPage_general_group_insert_new_line_before_finally_statements;
// public static String ControlStatementsTabPage_general_group_insert_new_line_before_while_in_do_statements;
// public static String ControlStatementsTabPage_if_else_group_title;
// public static String ControlStatementsTabPage_if_else_group_keep_then_on_same_line;
// public static String ControlStatementsTabPage_if_else_group_keep_simple_if_on_one_line;
// public static String ControlStatementsTabPage_if_else_group_keep_else_on_same_line;
// public static String ControlStatementsTabPage_if_else_group_keep_else_if_on_one_line;
// public static String ControlStatementsTabPage_if_else_group_keep_guardian_clause_on_one_line;
public static String CreateProfileDialog_status_message_profile_with_this_name_already_exists;
public static String CreateProfileDialog_status_message_profile_name_is_empty;
public static String CreateProfileDialog_dialog_title;
public static String CreateProfileDialog_profile_name_label_text;
public static String CreateProfileDialog_base_profile_label_text;
public static String CreateProfileDialog_open_edit_dialog_checkbox_text;
public static String IndentationTabPage_preview_header;
public static String IndentationTabPage_general_group_title;
public static String IndentationTabPage_general_group_option_tab_policy;
public static String IndentationTabPage_general_group_option_tab_policy_SPACE;
public static String IndentationTabPage_general_group_option_tab_policy_TAB;
public static String IndentationTabPage_general_group_option_tab_policy_MIXED;
public static String IndentationTabPage_general_group_option_tab_size;
public static String IndentationTabPage_general_group_option_indent_size;
public static String IndentationTabPage_field_alignment_group_title;
public static String IndentationTabPage_field_alignment_group_align_fields_in_columns;
public static String IndentationTabPage_indent_group_title;
public static String IndentationTabPage_class_group_option_indent_access_specifiers_within_class_body;
public static String IndentationTabPage_class_group_option_indent_declarations_compare_to_access_specifiers;
public static String IndentationTabPage_class_group_option_indent_declarations_within_enum_const;
public static String IndentationTabPage_class_group_option_indent_declarations_within_enum_decl;
public static String IndentationTabPage_block_group_option_indent_statements_compare_to_body;
public static String IndentationTabPage_block_group_option_indent_statements_compare_to_block;
public static String IndentationTabPage_switch_group_option_indent_statements_within_switch_body;
public static String IndentationTabPage_switch_group_option_indent_statements_within_case_body;
public static String IndentationTabPage_switch_group_option_indent_break_statements;
public static String IndentationTabPage_indent_empty_lines;
public static String IndentationTabPage_use_tabs_only_for_leading_indentations;
public static String ModifyDialog_dialog_title;
public static String ModifyDialog_apply_button;
public static String ModifyDialog_dialog_show_title;
public static String ModifyDialog_dialog_show_warning_builtin;
public static String ModifyDialog_tabpage_braces_title;
public static String ModifyDialog_tabpage_indentation_title;
public static String ModifyDialog_tabpage_whitespace_title;
public static String ModifyDialog_tabpage_blank_lines_title;
public static String ModifyDialog_tabpage_new_lines_title;
public static String ModifyDialog_tabpage_control_statements_title;
public static String ModifyDialog_tabpage_line_wrapping_title;
public static String ModifyDialog_tabpage_comments_title;
public static String ModifyDialogTabPage_preview_label_text;
public static String ModifyDialogTabPage_error_msg_values_text_unassigned;
public static String ModifyDialogTabPage_error_msg_values_items_text_unassigned;
public static String ModifyDialogTabPage_NumberPreference_error_invalid_key;
public static String ModifyDialogTabPage_NumberPreference_error_invalid_value;
// public static String NewLinesTabPage_preview_header;
// public static String NewLinesTabPage_newlines_group_title;
// public static String NewLinesTabPage_newlines_group_option_empty_class_body;
// public static String NewLinesTabPage_newlines_group_option_empty_annotation_decl_body;
// public static String NewLinesTabPage_newlines_group_option_empty_anonymous_class_body;
// public static String NewLinesTabPage_newlines_group_option_empty_enum_declaration;
// public static String NewLinesTabPage_newlines_group_option_empty_enum_constant;
// public static String NewLinesTabPage_newlines_group_option_empty_method_body;
// public static String NewLinesTabPage_newlines_group_option_empty_block;
// public static String NewLinesTabPage_newlines_group_option_empty_end_of_file;
// public static String NewLinesTabPage_empty_statement_group_title;
// public static String NewLinesTabPage_emtpy_statement_group_option_empty_statement_on_new_line;
// public static String NewLinesTabPage_arrayInitializer_group_title;
// public static String NewLinesTabPage_array_group_option_after_opening_brace_of_array_initializer;
// public static String NewLinesTabPage_array_group_option_before_closing_brace_of_array_initializer;
// public static String NewLinesTabPage_annotations_group_title;
// public static String NewLinesTabPage_annotations_group_option_after_annotation;
public static String ProfileManager_default_profile_name;
public static String ProfileManager_unmanaged_profile;
public static String ProfileManager_unmanaged_profile_with_name;
public static String RenameProfileDialog_status_message_profile_with_this_name_already_exists;
public static String RenameProfileDialog_status_message_profile_name_empty;
public static String RenameProfileDialog_dialog_title;
public static String RenameProfileDialog_dialog_label_enter_a_new_name;
public static String CPreview_formatter_exception;
static {
NLS.initializeMessages(BUNDLE_NAME, FormatterMessages.class);
}
}

View file

@ -0,0 +1,537 @@
###############################################################################
# Copyright (c) 2000, 2006 IBM Corporation and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# IBM Corporation - initial API and implementation
# istvan@benedek-home.de - 103706 [formatter] indent empty lines
# Aaron Luchko, aluchko@redhat.com - 105926 [Formatter] Exporting Unnamed profile fails silently
# Sergey Prigogin, Google
###############################################################################
#WhiteSpaceTabPage_assignments=Assignments
#WhiteSpaceTabPage_assignments_before_assignment_operator=before assignment operator
#WhiteSpaceTabPage_assignments_after_assignment_operator=after assignment operator
#WhiteSpaceTabPage_operators=Operators
#WhiteSpaceTabPage_operators_before_binary_operators=before binary operators
#WhiteSpaceTabPage_operators_after_binary_operators=after binary operators
#WhiteSpaceTabPage_operators_before_unary_operators=before unary operators
#WhiteSpaceTabPage_operators_after_unary_operators=after unary operators
#WhiteSpaceTabPage_operators_before_prefix_operators=before prefix operators
#WhiteSpaceTabPage_operators_after_prefix_operators=after prefix operators
#WhiteSpaceTabPage_operators_before_postfix_operators=before postfix operators
#WhiteSpaceTabPage_operators_after_postfix_operators=after postfix operators
#WhiteSpaceTabPage_classes=Classes
#WhiteSpaceTabPage_classes_before_opening_brace_of_a_class=before opening brace of a class
#WhiteSpaceTabPage_classes_before_opening_brace_of_anon_class=before opening brace of an anonymous class
#WhiteSpaceTabPage_classes_before_comma_implements=before comma in implements clause
#WhiteSpaceTabPage_classes_after_comma_implements=after comma in implements clause
#WhiteSpaceTabPage_methods=Methods
#WhiteSpaceTabPage_constructors=Constructors
#WhiteSpaceTabPage_fields=Fields
#WhiteSpaceTabPage_fields_before_comma=before comma in multiple field declarations
#WhiteSpaceTabPage_fields_after_comma=after comma in multiple field declarations
#WhiteSpaceTabPage_localvars=Local variables
#WhiteSpaceTabPage_localvars_before_comma=before comma in multiple local declarations
#WhiteSpaceTabPage_localvars_after_comma=after comma in multiple local declarations
#WhiteSpaceTabPage_arrayinit=Array initializers
#WhiteSpaceTabPage_arraydecls=Array declarations
#WhiteSpaceTabPage_arrayelem=Array element access
#WhiteSpaceTabPage_arrayalloc=Array allocation
#WhiteSpaceTabPage_calls=Function invocations
#WhiteSpaceTabPage_calls_before_comma_in_method_args=before comma in method arguments
#WhiteSpaceTabPage_calls_after_comma_in_method_args=after comma in method arguments
#WhiteSpaceTabPage_calls_before_comma_in_alloc=before comma in object allocation arguments
#WhiteSpaceTabPage_calls_after_comma_in_alloc=after comma in object allocation arguments
#WhiteSpaceTabPage_calls_before_comma_in_qalloc=before comma in explicit constructor call
#WhiteSpaceTabPage_calls_after_comma_in_qalloc=after comma in explicit constructor call
#WhiteSpaceTabPage_statements=Control statements
#WhiteSpaceTabPage_blocks=Blocks
#WhiteSpaceTabPage_switch='switch'
#WhiteSpaceTabPage_switch_before_case_colon=before colon in case
#WhiteSpaceTabPage_switch_before_default_colon=before colon in default
#WhiteSpaceTabPage_do='while' & 'do while'
#WhiteSpaceTabPage_synchronized='synchronized'
#WhiteSpaceTabPage_try='catch'
#WhiteSpaceTabPage_if='if else'
#WhiteSpaceTabPage_assert='assert'
#WhiteSpaceTabPage_for='for'
#WhiteSpaceTabPage_for_before_comma_init=before comma in initialization
#WhiteSpaceTabPage_for_after_comma_init=after comma in initialization
#WhiteSpaceTabPage_for_before_comma_inc=before comma in increments
#WhiteSpaceTabPage_for_after_comma_inc=after comma in increments
#WhiteSpaceTabPage_labels=Labels
#WhiteSpaceTabPage_annotations=Annotations
#WhiteSpaceTabPage_annotation_types=Annotation types
#WhiteSpaceTabPage_enums=Enum types
#WhiteSpaceTabPage_wildcardtype=Wildcard type
#WhiteSpaceTabPage_param_type_ref=Type reference
#WhiteSpaceTabPage_type_arguments=Type arguments
#WhiteSpaceTabPage_type_parameters=Type parameters
#WhiteSpaceTabPage_conditionals=Conditionals
#WhiteSpaceTabPage_typecasts=Type casts
#WhiteSpaceTabPage_parenexpr=Parenthesized expressions
#WhiteSpaceTabPage_declarations=Declarations
#WhiteSpaceTabPage_expressions=Expressions
#WhiteSpaceTabPage_arrays=Arrays
#WhiteSpaceTabPage_parameterized_types=Parameterized types
#WhiteSpaceTabPage_after_opening_brace=after opening brace
#WhiteSpaceTabPage_after_closing_brace=after closing brace
#WhiteSpaceTabPage_before_opening_brace=before opening brace
#WhiteSpaceTabPage_before_closing_brace=before closing brace
#WhiteSpaceTabPage_between_empty_braces=between empty braces
#WhiteSpaceTabPage_after_opening_paren=after opening parenthesis
#WhiteSpaceTabPage_after_closing_paren=after closing parenthesis
#WhiteSpaceTabPage_before_opening_paren=before opening parenthesis
#WhiteSpaceTabPage_before_closing_paren=before closing parenthesis
#WhiteSpaceTabPage_between_empty_parens=between empty parenthesis
#WhiteSpaceTabPage_after_opening_bracket=after opening bracket
#WhiteSpaceTabPage_before_opening_bracket=before opening bracket
#WhiteSpaceTabPage_before_closing_bracket=before closing bracket
#WhiteSpaceTabPage_between_empty_brackets=between empty brackets
#WhiteSpaceTabPage_before_comma_in_params=before comma in parameters
#WhiteSpaceTabPage_after_comma_in_params=after comma in parameters
#WhiteSpaceTabPage_before_comma_in_throws=before comma in 'throws' clause
#WhiteSpaceTabPage_after_comma_in_throws=after comma in 'throws' clause
#WhiteSpaceTabPage_before_ellipsis=before ellipsis in vararg parameters
#WhiteSpaceTabPage_after_ellipsis=after ellipsis in vararg parameters
#WhiteSpaceTabPage_before_comma=before comma
#WhiteSpaceTabPage_after_comma=after comma
#WhiteSpaceTabPage_after_semicolon=after semicolon
#WhiteSpaceTabPage_before_semicolon=before semicolon
#WhiteSpaceTabPage_before_colon=before colon
#WhiteSpaceTabPage_after_colon=after colon
#WhiteSpaceTabPage_before_question=before question mark
#WhiteSpaceTabPage_after_question=after question mark
#WhiteSpaceTabPage_before_at=before @
#WhiteSpaceTabPage_after_at=after @
#WhiteSpaceTabPage_after_opening_angle_bracket=after opening angle bracket
#WhiteSpaceTabPage_after_closing_angle_bracket=after closing angle bracket
#WhiteSpaceTabPage_before_opening_angle_bracket=before opening angle bracket
#WhiteSpaceTabPage_before_closing_angle_bracket=before closing angle bracket
#WhiteSpaceTabPage_before_parenthesized_expressions=before parenthesized expressions
#WhiteSpaceTabPage_before_and_list=before '&' in type bounds
#WhiteSpaceTabPage_after_and_list=after '&' in type bounds
#WhiteSpaceTabPage_enum_decl_before_opening_brace=before opening brace in declaration
#WhiteSpaceTabPage_enum_decl_before_comma=before comma between constants
#WhiteSpaceTabPage_enum_decl_after_comma=after comma between constants
#WhiteSpaceTabPage_enum_const_arg_before_opening_paren=before opening parenthesis in constant arguments
#WhiteSpaceTabPage_enum_const_arg_after_opening_paren=after opening parenthesis in constant arguments
#WhiteSpaceTabPage_enum_const_arg_between_empty_parens=between empty parenthesis in constant arguments
#WhiteSpaceTabPage_enum_const_arg_before_comma=before comma in constant arguments
#WhiteSpaceTabPage_enum_const_arg_after_comma=after comma in constant arguments
#WhiteSpaceTabPage_enum_const_arg_before_closing_paren=before closing parenthesis in constant arguments
#WhiteSpaceTabPage_enum_const_before_opening_brace=before opening brace of constant body
#WhiteSpaceTabPage_annot_type_method_before_opening_paren=before opening parenthesis in annotation type members
#WhiteSpaceTabPage_annot_type_method_between_empty_parens=between parenthesis in annotation type members
#WhiteSpaceTabPage_sort_by_c_element=Sort options by C element
#WhiteSpaceTabPage_sort_by_syntax_element=Sort options by Syntax element
#WhiteSpaceOptions_before=Before
#WhiteSpaceOptions_after=After
#WhiteSpaceOptions_operator=Operator
#WhiteSpaceOptions_assignment_operator=Assignment operator
#WhiteSpaceOptions_binary_operator=Binary operator
#WhiteSpaceOptions_unary_operator=Unary operator
#WhiteSpaceOptions_prefix_operator=Prefix operator
#WhiteSpaceOptions_postfix_operator=Postfix operator
#WhiteSpaceOptions_opening_paren=Opening parenthesis
#WhiteSpaceOptions_catch='catch'
#WhiteSpaceOptions_for='for'
#WhiteSpaceOptions_if='if'
#WhiteSpaceOptions_switch='switch'
#WhiteSpaceOptions_synchronized='synchronized'
#WhiteSpaceOptions_while='while'
#WhiteSpaceOptions_assert='assert'
#WhiteSpaceOptions_member_function_declaration=Member function declaration
#WhiteSpaceOptions_constructor=Constructor
#WhiteSpaceOptions_method=Method
#WhiteSpaceOptions_method_call=Method call
#WhiteSpaceOptions_paren_expr=Parenthesized expression
#WhiteSpaceOptions_enum_constant_body=Enum constant body
#WhiteSpaceOptions_enum_constant_arguments=Enum constant arguments
#WhiteSpaceOptions_enum_declaration=Enum declaration
#WhiteSpaceOptions_annotation_modifier=Annotation
#WhiteSpaceOptions_annotation_modifier_args=Annotation arguments
#WhiteSpaceOptions_annotation_type_member=Annotation type member
#WhiteSpaceOptions_annotation_type=Annotation type
#WhiteSpaceOptions_type_cast=Type cast
#WhiteSpaceOptions_parameterized_type=Parameterized type
#WhiteSpaceOptions_type_arguments=Type arguments
#WhiteSpaceOptions_type_parameters=Type parameters
#WhiteSpaceOptions_vararg_parameter=Vararg parameters
#WhiteSpaceOptions_closing_paren=Closing parenthesis
#WhiteSpaceOptions_opening_brace=Opening brace
#WhiteSpaceOptions_closing_brace=Closing brace
#WhiteSpaceOptions_opening_bracket=Opening bracket
#WhiteSpaceOptions_closing_bracket=Closing bracket
#WhiteSpaceOptions_class_decl=Type declaration
#WhiteSpaceOptions_anon_class_decl=Anonymous type declaration
#WhiteSpaceOptions_initializer=Array initializer
#WhiteSpaceOptions_block=Block
#WhiteSpaceOptions_array_decl=Array declaration
#WhiteSpaceOptions_array_element_access=Array element access
#WhiteSpaceOptions_array_alloc=Array allocation
#WhiteSpaceOptions_array_init=Array initializer
#WhiteSpaceOptions_arguments=Arguments
#WhiteSpaceOptions_initialization=Initialization
#WhiteSpaceOptions_incrementation=Increment
#WhiteSpaceOptions_parameters=Parameters
#WhiteSpaceOptions_explicit_constructor_call=Explicit constructor call
#WhiteSpaceOptions_alloc_expr=Allocation expression
#WhiteSpaceOptions_throws='throws' clause
#WhiteSpaceOptions_mult_decls=Multiple declarations
#WhiteSpaceOptions_local_vars=Local variables
#WhiteSpaceOptions_fields=Fields
#WhiteSpaceOptions_return='return'
#WhiteSpaceOptions_implements_clause='extends'/'implements' clause
#WhiteSpaceOptions_colon=Colon
#WhiteSpaceOptions_conditional=Conditional
#WhiteSpaceOptions_wildcard=Wildcard type
#WhiteSpaceOptions_label=Label
#WhiteSpaceOptions_comma=Comma
#WhiteSpaceOptions_semicolon=Semicolon
#WhiteSpaceOptions_question_mark=Question mark
#WhiteSpaceOptions_between_empty_parens=Between empty parenthesis
#WhiteSpaceOptions_between_empty_braces=Between empty braces
#WhiteSpaceOptions_between_empty_brackets=Between empty brackets
#WhiteSpaceOptions_constructor_decl=Constructor declaration
#WhiteSpaceOptions_method_decl=Method declaration
#WhiteSpaceOptions_case='case'
#WhiteSpaceOptions_default='default'
#WhiteSpaceOptions_statements=Statements
#WhiteSpaceOptions_before_opening_paren=Before opening parenthesis
#WhiteSpaceOptions_after_opening_paren=After opening parenthesis
#WhiteSpaceOptions_before_closing_paren=Before closing parenthesis
#WhiteSpaceOptions_after_closing_paren=After closing parenthesis
#WhiteSpaceOptions_before_opening_brace=Before opening brace
#WhiteSpaceOptions_after_opening_brace=After opening brace
#WhiteSpaceOptions_after_closing_brace=After closing brace
#WhiteSpaceOptions_before_closing_brace=Before closing brace
#WhiteSpaceOptions_before_opening_bracket=Before opening bracket
#WhiteSpaceOptions_after_opening_bracket=After opening bracket
#WhiteSpaceOptions_before_closing_bracket=Before closing bracket
#WhiteSpaceOptions_before_opening_angle_bracket=Before opening angle bracket
#WhiteSpaceOptions_after_opening_angle_bracket=After opening angle bracket
#WhiteSpaceOptions_before_closing_angle_bracket=Before closing angle bracket
#WhiteSpaceOptions_return_with_parenthesized_expression=parenthesized expression
#WhiteSpaceOptions_after_closing_angle_bracket=After closing angle bracket
#WhiteSpaceOptions_before_operator=Before operator
#WhiteSpaceOptions_after_operator=After operator
#WhiteSpaceOptions_before_comma=Before comma
#WhiteSpaceOptions_after_comma=After comma
#WhiteSpaceOptions_after_colon=After colon
#WhiteSpaceOptions_before_colon=Before colon
#WhiteSpaceOptions_before_semicolon=Before semicolon
#WhiteSpaceOptions_after_semicolon=After semicolon
#WhiteSpaceOptions_before_question_mark=Before question mark
#WhiteSpaceOptions_after_question_mark=After question mark
#WhiteSpaceOptions_before_at=Before @
#WhiteSpaceOptions_after_at=After @
#WhiteSpaceOptions_before_and=Before & list
#WhiteSpaceOptions_after_and=After & list
#WhiteSpaceOptions_before_ellipsis=Before Ellipsis
#WhiteSpaceOptions_after_ellipsis=After Ellipsis
#WhiteSpaceTabPage_insert_space=&Insert space:
#LineWrappingTabPage_compact_if_else=Compact 'if else'
#LineWrappingTabPage_extends_clause='extends' clause
#LineWrappingTabPage_enum_constant_arguments=Constant arguments
#LineWrappingTabPage_enum_constants=Constants
#LineWrappingTabPage_implements_clause='implements' clause
#LineWrappingTabPage_parameters=Parameters
#LineWrappingTabPage_arguments=Arguments
#LineWrappingTabPage_qualified_invocations=Qualified invocations
#LineWrappingTabPage_throws_clause='throws' clause
#LineWrappingTabPage_object_allocation=Object allocation arguments
#LineWrappingTabPage_qualified_object_allocation=Qualified object allocation arguments
#LineWrappingTabPage_array_init=Array initializers
#LineWrappingTabPage_explicit_constructor_invocations=Explicit constructor invocations
#LineWrappingTabPage_conditionals=Conditionals
#LineWrappingTabPage_binary_exprs=Binary expressions
#LineWrappingTabPage_indentation_default=Default indentation
#LineWrappingTabPage_indentation_on_column=Indent on column
#LineWrappingTabPage_indentation_by_one=Indent by one
#LineWrappingTabPage_class_decls=Class Declarations
#LineWrappingTabPage_method_decls=Method Declarations
#LineWrappingTabPage_constructor_decls=Constructor declarations
#LineWrappingTabPage_function_calls=Function Calls
#LineWrappingTabPage_expressions=Expressions
#LineWrappingTabPage_statements=Statements
#LineWrappingTabPage_enum_decls='enum' declaration
#LineWrappingTabPage_wrapping_policy_label_text=Lin&e wrapping policy:
#LineWrappingTabPage_indentation_policy_label_text=Indent&ation policy:
#LineWrappingTabPage_force_split_checkbox_text=&Force split
#LineWrappingTabPage_force_split_checkbox_multi_text=&Force split
#LineWrappingTabPage_line_width_for_preview_label_text=&Set line width for preview window:
#LineWrappingTabPage_group=Settings for {0}
#LineWrappingTabPage_multi_group=Settings for {0} ({1} items)
#LineWrappingTabPage_multiple_selections=Settings for multiple selections ({0} items)
#LineWrappingTabPage_occurences={0} ({1} of {2})
#LineWrappingTabPage_splitting_do_not_split=Do not wrap
#LineWrappingTabPage_splitting_wrap_when_necessary=Wrap only when necessary
#LineWrappingTabPage_splitting_always_wrap_first_others_when_necessary=Always wrap first element, others when necessary
#LineWrappingTabPage_splitting_wrap_always=Wrap all elements, every element on a new line
#LineWrappingTabPage_splitting_wrap_always_indent_all_but_first=Wrap all elements, indent all but the first element
#LineWrappingTabPage_splitting_wrap_always_except_first_only_if_necessary=Wrap all elements, except first element if not necessary
#LineWrappingTabPage_width_indent=Line width and indentation levels
#LineWrappingTabPage_width_indent_option_max_line_width=Ma&ximum line width:
#LineWrappingTabPage_width_indent_option_default_indent_wrapped=Defa&ult indentation for wrapped lines:
#LineWrappingTabPage_width_indent_option_default_indent_array=Default indentation for arra&y initializers:
#LineWrappingTabPage_error_invalid_value=The key ''{0}'' contained an invalid value; resetting to defaults.
#LineWrappingTabPage_enum_superinterfaces='implements' clause
#LineWrappingTabPage_assignment_alignment=Assignments
AlreadyExistsDialog_message_profile_already_exists=A profile with this name already exists.
AlreadyExistsDialog_message_profile_name_empty=Profile name is empty
AlreadyExistsDialog_dialog_title=Load Profile
AlreadyExistsDialog_dialog_label=A profile with the name ''{0}'' already exists in this workspace. What would you like to do?
AlreadyExistsDialog_rename_radio_button_desc=&Rename the imported profile:
AlreadyExistsDialog_overwrite_radio_button_desc=&Overwrite the existing profile.
#BlankLinesTabPage_preview_header=Blank Lines
#BlankLinesTabPage_compilation_unit_group_title=Blank lines in compilation unit
#BlankLinesTabPage_compilation_unit_option_before_package=Before p&ackage declaration:
#BlankLinesTabPage_compilation_unit_option_after_package=After packa&ge declaration:
#BlankLinesTabPage_compilation_unit_option_before_import=&Before import declaration:
#BlankLinesTabPage_compilation_unit_option_after_import=After import de&claration:
#BlankLinesTabPage_compilation_unit_option_between_type_declarations=Between class declarat&ions:
#BlankLinesTabPage_class_group_title=Blank lines within class declarations
#BlankLinesTabPage_class_option_before_first_decl=Before &first declaration:
#BlankLinesTabPage_class_option_before_decls_of_same_kind=Before declarations of the same &kind:
#BlankLinesTabPage_class_option_before_member_class_decls=Before member cla&ss declarations:
#BlankLinesTabPage_class_option_before_field_decls=B&efore field declarations:
#BlankLinesTabPage_class_option_before_method_decls=Before met&hod declarations:
#BlankLinesTabPage_class_option_at_beginning_of_method_body= At beginning of method bod&y:
#BlankLinesTabPage_blank_lines_group_title=Existing blank lines
#BlankLinesTabPage_blank_lines_option_empty_lines_to_preserve=N&umber of empty lines to preserve:
#BracesTabPage_preview_header=Braces
#BracesTabPage_position_same_line=Same line
#BracesTabPage_position_next_line=Next line
#BracesTabPage_position_next_line_indented=Next line indented
#BracesTabPage_position_next_line_on_wrap=Next line on wrap
#BracesTabPage_group_brace_positions_title=Brace positions
#BracesTabPage_option_class_declaration=&Class or interface declaration:
#BracesTabPage_option_anonymous_class_declaration=Anon&ymous class declaration:
#BracesTabPage_option_method_declaration=Met&hod declaration:
#BracesTabPage_option_constructor_declaration=Constr&uctor declaration:
#BracesTabPage_option_blocks=&Blocks:
#BracesTabPage_option_blocks_in_case=Bloc&ks in case statement:
#BracesTabPage_option_switch_case='&switch' statement:
#BracesTabPage_option_array_initializer=Array initiali&zer:
#BracesTabPage_option_keep_empty_array_initializer_on_one_line=Keep empty array &initializer on one line
#BracesTabPage_option_enum_declaration=&Enum declaration:
#BracesTabPage_option_enumconst_declaration=Enum c&onstant body:
#BracesTabPage_option_annotation_type_declaration=&Annotation type declaration:
CodingStyleConfigurationBlock_save_profile_dialog_title=Export Profile
CodingStyleConfigurationBlock_save_profile_error_title=Export Profile
CodingStyleConfigurationBlock_save_profile_error_message=Could not export the profiles.
CodingStyleConfigurationBlock_load_profile_dialog_title=Import Profile
CodingStyleConfigurationBlock_load_profile_error_title=Import Profile
CodingStyleConfigurationBlock_load_profile_error_message=Import failed. Not a valid profile.
CodingStyleConfigurationBlock_load_profile_error_too_new_title=Importing Profile
CodingStyleConfigurationBlock_load_profile_error_too_new_message=This profile has been created with \
a more recent CDT build than the one you are using. Due to changes in the code formatter, \
some older settings might be reset to their default values and newer settings are ignored. Please note \
that upgrading profiles from older to newer builds is fully supported.
CodingStyleConfigurationBlock_preview_title=A sample source file for the code formatter preview
CodingStyleConfigurationBlock_save_profile_overwrite_title=Export Profile
CodingStyleConfigurationBlock_save_profile_overwrite_message={0} " already exists.\nDo you want to replace it?"
CodingStyleConfigurationBlock_edit_button_desc=&Edit...
CodingStyleConfigurationBlock_show_button_desc=&Show...
CodingStyleConfigurationBlock_rename_button_desc=Re&name...
CodingStyleConfigurationBlock_remove_button_desc=&Remove
CodingStyleConfigurationBlock_new_button_desc=Ne&w...
CodingStyleConfigurationBlock_load_button_desc=I&mport...
CodingStyleConfigurationBlock_save_button_desc=E&xport...
CodingStyleConfigurationBlock_preview_label_text=Prev&iew:
CodingStyleConfigurationBlock_error_reading_xml_message=Problems reading profiles from XML
CodingStyleConfigurationBlock_error_serializing_xml_message=Problems serializing the profiles to XML
CodingStyleConfigurationBlock_delete_confirmation_title=Confirm Remove
CodingStyleConfigurationBlock_delete_confirmation_question=Are you sure you want to remove profile ''{0}''?
CustomCodeFormatterBlock_formatter_name=Code &Formatter:
CustomCodeFormatterBlock_no_formatter=(NONE)
CustomCodeFormatterBlock_contributed_formatter_warning=Some formatters may not respect all code style settings.
#CommentsTabPage_group1_title=General settings
#CommentsTabPage_enable_comment_formatting=Enable &comment formatting
#CommentsTabPage_format_header=Format &header comment
#CommentsTabPage_format_html=Format HTML ta&gs
#CommentsTabPage_format_code_snippets=Format &C code snippets
#CommentsTabPage_clear_blank_lines=Clear &blank lines in comments
#CommentsTabPage_group3_title=Line width
#CommentsTabPage_line_width=Ma&ximum line width for comments:
#ControlStatementsTabPage_preview_header=If...else
#ControlStatementsTabPage_general_group_title=General
#ControlStatementsTabPage_general_group_insert_new_line_before_else_statements=Insert new line before '&else' in an 'if' statement
#ControlStatementsTabPage_general_group_insert_new_line_before_catch_statements=Insert new line before '&catch' in a 'try' statement
#ControlStatementsTabPage_general_group_insert_new_line_before_finally_statements=Insert new line before '&finally' in a 'try' statement
#ControlStatementsTabPage_general_group_insert_new_line_before_while_in_do_statements=Insert new line before 'w&hile' in a 'do' statement
#ControlStatementsTabPage_if_else_group_title='if else'
#ControlStatementsTabPage_if_else_group_keep_then_on_same_line=Keep 'then' statement &on same line
#ControlStatementsTabPage_if_else_group_keep_simple_if_on_one_line=Keep &simple 'if' on one line
#ControlStatementsTabPage_if_else_group_keep_else_on_same_line=Keep 'else' st&atement on same line
#ControlStatementsTabPage_if_else_group_keep_else_if_on_one_line=&Keep 'else if' on one line
#ControlStatementsTabPage_if_else_group_keep_guardian_clause_on_one_line=Keep 'return' or 'throw' cla&use on one line
CreateProfileDialog_status_message_profile_with_this_name_already_exists=A profile with this name already exists.
CreateProfileDialog_status_message_profile_name_is_empty=Profile name is empty
CreateProfileDialog_dialog_title=New Code Formatter Profile
CreateProfileDialog_profile_name_label_text=&Profile name:
CreateProfileDialog_base_profile_label_text=I&nitialize settings with the following profile:
CreateProfileDialog_open_edit_dialog_checkbox_text=&Open the edit dialog now
IndentationTabPage_preview_header=Indentation
IndentationTabPage_general_group_title=General settings
IndentationTabPage_general_group_option_tab_policy=Tab polic&y:
IndentationTabPage_general_group_option_tab_policy_SPACE=Spaces only
IndentationTabPage_general_group_option_tab_policy_TAB=Tabs only
IndentationTabPage_general_group_option_tab_policy_MIXED=Mixed
IndentationTabPage_general_group_option_tab_size=Tab &size:
IndentationTabPage_general_group_option_indent_size=&Indentation size:
IndentationTabPage_field_alignment_group_title=Alignment of fields in class declarations
IndentationTabPage_field_alignment_group_align_fields_in_columns=&Align fields in columns
IndentationTabPage_indent_group_title=Indent
IndentationTabPage_class_group_option_indent_access_specifiers_within_class_body='public', 'protected', 'private' within class &body
IndentationTabPage_class_group_option_indent_declarations_compare_to_access_specifiers=De&clarations relative to 'public', 'protected', 'private'
IndentationTabPage_class_group_option_indent_declarations_within_enum_const=Declarations within en&um constants
IndentationTabPage_class_group_option_indent_declarations_within_enum_decl=Declarations within enum declaration
IndentationTabPage_block_group_option_indent_statements_compare_to_body=Stat&ements within method/constructor body
IndentationTabPage_block_group_option_indent_statements_compare_to_block=Statements within bl&ocks
IndentationTabPage_indent_empty_lines=Empty lines
IndentationTabPage_switch_group_option_indent_statements_within_switch_body=Statements wit&hin 'switch' body
IndentationTabPage_switch_group_option_indent_statements_within_case_body=Statements within 'case' bo&dy
IndentationTabPage_switch_group_option_indent_break_statements='brea&k' statements
IndentationTabPage_use_tabs_only_for_leading_indentations=Use tabs only for leading indentations
ModifyDialog_dialog_title=Edit Profile ''{0}''
ModifyDialog_apply_button=Apply
ModifyDialog_dialog_show_title=Show Profile ''{0}''
ModifyDialog_dialog_show_warning_builtin=This is a built-in profile, you will be prompted to enter a new name after closing this dialog.
ModifyDialog_tabpage_braces_title=B&races
ModifyDialog_tabpage_indentation_title=In&dentation
ModifyDialog_tabpage_whitespace_title=&White Space
ModifyDialog_tabpage_blank_lines_title=Bla&nk Lines
ModifyDialog_tabpage_new_lines_title=New &Lines
ModifyDialog_tabpage_control_statements_title=Con&trol Statements
ModifyDialog_tabpage_line_wrapping_title=Line Wra&pping
ModifyDialog_tabpage_comments_title=Co&mments
ModifyDialogTabPage_preview_label_text=Pre&view:
ModifyDialogTabPage_error_msg_values_text_unassigned=Values and text must be assigned.
ModifyDialogTabPage_error_msg_values_items_text_unassigned=Values, items and text must be assigned.
ModifyDialogTabPage_NumberPreference_error_invalid_key=The key {0} does not yield a valid integer value.
ModifyDialogTabPage_NumberPreference_error_invalid_value=Invalid value: Please enter a number between {0} and {1}.
#NewLinesTabPage_preview_header=New Lines
#NewLinesTabPage_newlines_group_title=Insert new line
#NewLinesTabPage_newlines_group_option_empty_class_body=in empty &class body
#NewLinesTabPage_newlines_group_option_empty_annotation_decl_body=in empty annotation body
#NewLinesTabPage_newlines_group_option_empty_anonymous_class_body=in empty &anonymous class body
#NewLinesTabPage_newlines_group_option_empty_enum_declaration=in empty &enum declaration
#NewLinesTabPage_newlines_group_option_empty_enum_constant=in empty enum c&onstant body
#NewLinesTabPage_newlines_group_option_empty_method_body=in empt&y method body
#NewLinesTabPage_newlines_group_option_empty_block=in empty &block
#NewLinesTabPage_newlines_group_option_empty_end_of_file=at end of &file
#NewLinesTabPage_empty_statement_group_title=Empty statements
#NewLinesTabPage_emtpy_statement_group_option_empty_statement_on_new_line=Put empty &statement on new line
#NewLinesTabPage_arrayInitializer_group_title=Array initializers
#NewLinesTabPage_array_group_option_after_opening_brace_of_array_initializer=Insert new line after openin&g brace of array initializer
#NewLinesTabPage_array_group_option_before_closing_brace_of_array_initializer=Insert new line before closing brace of array initiali&zer
#NewLinesTabPage_annotations_group_title=Annotations
#NewLinesTabPage_annotations_group_option_after_annotation=&Insert new line after annotations
ProfileManager_default_profile_name=Default [built-in]
ProfileManager_unmanaged_profile=Unmanaged profile
ProfileManager_unmanaged_profile_with_name=Unmanaged profile "{0}"
RenameProfileDialog_status_message_profile_with_this_name_already_exists=A profile with this name already exists.
RenameProfileDialog_status_message_profile_name_empty=Profile name is empty
RenameProfileDialog_dialog_title=Rename Profile
RenameProfileDialog_dialog_label_enter_a_new_name=Please &enter a new name:
CPreview_formatter_exception=The formatter threw an unhandled exception while formatting the preview.

View file

@ -0,0 +1,181 @@
/*******************************************************************************
* Copyright (c) 2000, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* istvan@benedek-home.de - 103706 [formatter] indent empty lines
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences.formatter;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.jface.text.Assert;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants;
public class IndentationTabPage extends ModifyDialogTabPage {
// private final String PREVIEW=
// createPreviewHeader(FormatterMessages.IndentationTabPage_preview_header) +
// "class Example {" + //$NON-NLS-1$
// " int [] myArray= {1,2,3,4,5,6};" + //$NON-NLS-1$
// " int theInt= 1;" + //$NON-NLS-1$
// " String someString= \"Hello\";" + //$NON-NLS-1$
// " double aDouble= 3.0;" + //$NON-NLS-1$
// " void foo(int a, int b, int c, int d, int e, int f) {" + //$NON-NLS-1$
// " switch(a) {" + //$NON-NLS-1$
// " case 0: " + //$NON-NLS-1$
// " Other.doFoo();" + //$NON-NLS-1$
// " break;" + //$NON-NLS-1$
// " default:" + //$NON-NLS-1$
// " Other.doBaz();" + //$NON-NLS-1$
// " }" + //$NON-NLS-1$
// " }" + //$NON-NLS-1$
// " void bar(List v) {" + //$NON-NLS-1$
// " for (int i= 0; i < 10; i++) {" + //$NON-NLS-1$
// " v.add(new Integer(i));" + //$NON-NLS-1$
// " }" + //$NON-NLS-1$
// " }" + //$NON-NLS-1$
// "}" + //$NON-NLS-1$
// "\n" + //$NON-NLS-1$
// "enum MyEnum {" + //$NON-NLS-1$
// " UNDEFINED(0) {" + //$NON-NLS-1$
// " void foo() {}" + //$NON-NLS-1$
// " }" + //$NON-NLS-1$
// "}" + //$NON-NLS-1$
// "@interface MyAnnotation {" + //$NON-NLS-1$
// " int count() default 1;" + //$NON-NLS-1$
// "}";//$NON-NLS-1$
// private CompilationUnitPreview fPreview;
private String fOldTabChar= null;
public IndentationTabPage(ModifyDialog modifyDialog, Map workingValues) {
super(modifyDialog, workingValues);
}
protected void doCreatePreferences(Composite composite, int numColumns) {
final Group generalGroup= createGroup(numColumns, composite, FormatterMessages.IndentationTabPage_general_group_title);
final String[] tabPolicyValues= new String[] {CCorePlugin.SPACE, CCorePlugin.TAB, DefaultCodeFormatterConstants.MIXED};
final String[] tabPolicyLabels= new String[] {
FormatterMessages.IndentationTabPage_general_group_option_tab_policy_SPACE,
FormatterMessages.IndentationTabPage_general_group_option_tab_policy_TAB,
FormatterMessages.IndentationTabPage_general_group_option_tab_policy_MIXED
};
final ComboPreference tabPolicy= createComboPref(generalGroup, numColumns, FormatterMessages.IndentationTabPage_general_group_option_tab_policy, DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, tabPolicyValues, tabPolicyLabels);
final CheckboxPreference onlyForLeading= createCheckboxPref(generalGroup, numColumns, FormatterMessages.IndentationTabPage_use_tabs_only_for_leading_indentations, DefaultCodeFormatterConstants.FORMATTER_USE_TABS_ONLY_FOR_LEADING_INDENTATIONS, FALSE_TRUE);
final NumberPreference indentSize= createNumberPref(generalGroup, numColumns, FormatterMessages.IndentationTabPage_general_group_option_indent_size, DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, 0, 32);
final NumberPreference tabSize= createNumberPref(generalGroup, numColumns, FormatterMessages.IndentationTabPage_general_group_option_tab_size, DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, 0, 32);
String tabchar= (String) fWorkingValues.get(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR);
updateTabPreferences(tabchar, tabSize, indentSize, onlyForLeading);
tabPolicy.addObserver(new Observer() {
public void update(Observable o, Object arg) {
updateTabPreferences((String) arg, tabSize, indentSize, onlyForLeading);
}
});
tabSize.addObserver(new Observer() {
public void update(Observable o, Object arg) {
indentSize.updateWidget();
}
});
// final Group typeMemberGroup= createGroup(numColumns, composite, FormatterMessages.IndentationTabPage_field_alignment_group_title);
// createCheckboxPref(typeMemberGroup, numColumns, FormatterMessages.IndentationTabPage_field_alignment_group_align_fields_in_columns, DefaultCodeFormatterConstants.FORMATTER_ALIGN_TYPE_MEMBERS_ON_COLUMNS, FALSE_TRUE);
final Group classGroup = createGroup(numColumns, composite, FormatterMessages.IndentationTabPage_indent_group_title);
createCheckboxPref(classGroup, numColumns, FormatterMessages.IndentationTabPage_class_group_option_indent_access_specifiers_within_class_body, DefaultCodeFormatterConstants.FORMATTER_INDENT_ACCESS_SPECIFIER_COMPARE_TO_TYPE_HEADER, FALSE_TRUE);
createCheckboxPref(classGroup, numColumns, FormatterMessages.IndentationTabPage_class_group_option_indent_declarations_compare_to_access_specifiers, DefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ACCESS_SPECIFIER, FALSE_TRUE);
createCheckboxPref(classGroup, numColumns, FormatterMessages.IndentationTabPage_class_group_option_indent_declarations_within_enum_decl, DefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ENUM_DECLARATION_HEADER, FALSE_TRUE);
createCheckboxPref(classGroup, numColumns, FormatterMessages.IndentationTabPage_class_group_option_indent_declarations_within_enum_const, DefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ENUM_CONSTANT_HEADER, FALSE_TRUE);
createCheckboxPref(classGroup, numColumns, FormatterMessages.IndentationTabPage_block_group_option_indent_statements_compare_to_body, DefaultCodeFormatterConstants.FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BODY, FALSE_TRUE);
createCheckboxPref(classGroup, numColumns, FormatterMessages.IndentationTabPage_block_group_option_indent_statements_compare_to_block, DefaultCodeFormatterConstants.FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BLOCK, FALSE_TRUE);
createCheckboxPref(classGroup, numColumns, FormatterMessages.IndentationTabPage_switch_group_option_indent_statements_within_switch_body, DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_SWITCH, FALSE_TRUE);
createCheckboxPref(classGroup, numColumns, FormatterMessages.IndentationTabPage_switch_group_option_indent_statements_within_case_body, DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_CASES, FALSE_TRUE);
createCheckboxPref(classGroup, numColumns, FormatterMessages.IndentationTabPage_switch_group_option_indent_break_statements, DefaultCodeFormatterConstants.FORMATTER_INDENT_BREAKS_COMPARE_TO_CASES, FALSE_TRUE);
createCheckboxPref(classGroup, numColumns, FormatterMessages.IndentationTabPage_indent_empty_lines, DefaultCodeFormatterConstants.FORMATTER_INDENT_EMPTY_LINES, FALSE_TRUE);
}
public void initializePage() {
// fPreview.setPreviewText(PREVIEW);
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.ui.preferences.formatter.ModifyDialogTabPage#doCreateCPreview(org.eclipse.swt.widgets.Composite)
*/
protected CPreview doCreateCPreview(Composite parent) {
// fPreview= new CompilationUnitPreview(fWorkingValues, parent);
// return fPreview;
return null;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.ui.preferences.formatter.ModifyDialogTabPage#doUpdatePreview()
*/
protected void doUpdatePreview() {
// fPreview.update();
}
private void updateTabPreferences(String tabPolicy, NumberPreference tabPreference, NumberPreference indentPreference, CheckboxPreference onlyForLeading) {
/*
* If the tab-char is SPACE (or TAB), INDENTATION_SIZE
* preference is not used by the core formatter. We piggy back the
* visual tab length setting in that preference in that case. If the
* user selects MIXED, we use the previous TAB_SIZE preference as the
* new INDENTATION_SIZE (as this is what it really is) and set the
* visual tab size to the value piggy backed in the INDENTATION_SIZE
* preference. See also CodeFormatterUtil.
*/
if (DefaultCodeFormatterConstants.MIXED.equals(tabPolicy)) {
if (CCorePlugin.SPACE.equals(fOldTabChar) || CCorePlugin.TAB.equals(fOldTabChar))
swapTabValues();
tabPreference.setEnabled(true);
tabPreference.setKey(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE);
indentPreference.setEnabled(true);
indentPreference.setKey(DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE);
onlyForLeading.setEnabled(true);
} else if (CCorePlugin.SPACE.equals(tabPolicy)) {
if (DefaultCodeFormatterConstants.MIXED.equals(fOldTabChar))
swapTabValues();
tabPreference.setEnabled(true);
tabPreference.setKey(DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE);
indentPreference.setEnabled(true);
indentPreference.setKey(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE);
onlyForLeading.setEnabled(false);
} else if (CCorePlugin.TAB.equals(tabPolicy)) {
if (DefaultCodeFormatterConstants.MIXED.equals(fOldTabChar))
swapTabValues();
tabPreference.setEnabled(true);
tabPreference.setKey(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE);
indentPreference.setEnabled(false);
indentPreference.setKey(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE);
onlyForLeading.setEnabled(true);
} else {
Assert.isTrue(false);
}
fOldTabChar= tabPolicy;
}
private void swapTabValues() {
Object tabSize= fWorkingValues.get(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE);
Object indentSize= fWorkingValues.get(DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE);
fWorkingValues.put(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, indentSize);
fWorkingValues.put(DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE, tabSize);
}
}

View file

@ -0,0 +1,267 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences.formatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.StatusDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.cdt.internal.ui.util.Messages;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.ui.preferences.formatter.ProfileManager.Profile;
public class ModifyDialog extends StatusDialog {
/**
* The keys to retrieve the preferred area from the dialog settings.
*/
private static final String DS_KEY_PREFERRED_WIDTH= CUIPlugin.PLUGIN_ID + "formatter_page.modify_dialog.preferred_width"; //$NON-NLS-1$
private static final String DS_KEY_PREFERRED_HEIGHT= CUIPlugin.PLUGIN_ID + "formatter_page.modify_dialog.preferred_height"; //$NON-NLS-1$
private static final String DS_KEY_PREFERRED_X= CUIPlugin.PLUGIN_ID + "formatter_page.modify_dialog.preferred_x"; //$NON-NLS-1$
private static final String DS_KEY_PREFERRED_Y= CUIPlugin.PLUGIN_ID + "formatter_page.modify_dialog.preferred_y"; //$NON-NLS-1$
/**
* The key to store the number (beginning at 0) of the tab page which had the
* focus last time.
*/
private static final String DS_KEY_LAST_FOCUS= CUIPlugin.PLUGIN_ID + "formatter_page.modify_dialog.last_focus"; //$NON-NLS-1$
private final String fTitle;
private final boolean fNewProfile;
private Profile fProfile;
private final Map fWorkingValues;
private IStatus fStandardStatus;
protected final List fTabPages;
final IDialogSettings fDialogSettings;
// private TabFolder fTabFolder;
private ProfileManager fProfileManager;
// private Button fApplyButton;
protected ModifyDialog(Shell parentShell, Profile profile, ProfileManager profileManager, boolean newProfile) {
super(parentShell);
fProfileManager= profileManager;
fNewProfile= newProfile;
setShellStyle(getShellStyle() | SWT.RESIZE | SWT.MAX );
fProfile= profile;
if (fProfile.isBuiltInProfile()) {
fStandardStatus= new Status(IStatus.INFO, CUIPlugin.getPluginId(), IStatus.OK, FormatterMessages.ModifyDialog_dialog_show_warning_builtin, null);
fTitle= Messages.format(FormatterMessages.ModifyDialog_dialog_show_title, profile.getName());
} else {
fStandardStatus= new Status(IStatus.OK, CUIPlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$
fTitle= Messages.format(FormatterMessages.ModifyDialog_dialog_title, profile.getName());
}
fWorkingValues= new HashMap(fProfile.getSettings());
updateStatus(fStandardStatus);
setStatusLineAboveButtons(false);
fTabPages= new ArrayList();
fDialogSettings= CUIPlugin.getDefault().getDialogSettings();
}
public void create() {
super.create();
int lastFocusNr= 0;
try {
lastFocusNr= fDialogSettings.getInt(DS_KEY_LAST_FOCUS);
if (lastFocusNr < 0) lastFocusNr= 0;
if (lastFocusNr > fTabPages.size() - 1) lastFocusNr= fTabPages.size() - 1;
} catch (NumberFormatException x) {
lastFocusNr= 0;
}
if (!fNewProfile) {
// fTabFolder.setSelection(lastFocusNr);
// ((ModifyDialogTabPage)fTabFolder.getSelection()[0].getData()).setInitialFocus();
}
}
protected void configureShell(Shell shell) {
super.configureShell(shell);
shell.setText(fTitle);
}
protected Control createDialogArea(Composite parent) {
final Composite composite= (Composite)super.createDialogArea(parent);
ModifyDialogTabPage tabPage = new IndentationTabPage(this, fWorkingValues);
tabPage.createContents(composite);
// fTabFolder = new TabFolder(composite, SWT.NONE);
// fTabFolder.setFont(composite.getFont());
// fTabFolder.setLayoutData(new GridData(GridData.FILL_BOTH));
//
// addTabPage(fTabFolder, FormatterMessages.ModifyDialog_tabpage_indentation_title, new IndentationTabPage(this, fWorkingValues));
// addTabPage(fTabFolder, FormatterMessages.ModifyDialog_tabpage_braces_title, new BracesTabPage(this, fWorkingValues));
// addTabPage(fTabFolder, FormatterMessages.ModifyDialog_tabpage_whitespace_title, new WhiteSpaceTabPage(this, fWorkingValues));
// addTabPage(fTabFolder, FormatterMessages.ModifyDialog_tabpage_blank_lines_title, new BlankLinesTabPage(this, fWorkingValues));
// addTabPage(fTabFolder, FormatterMessages.ModifyDialog_tabpage_new_lines_title, new NewLinesTabPage(this, fWorkingValues));
// addTabPage(fTabFolder, FormatterMessages.ModifyDialog_tabpage_control_statements_title, new ControlStatementsTabPage(this, fWorkingValues));
// addTabPage(fTabFolder, FormatterMessages.ModifyDialog_tabpage_line_wrapping_title, new LineWrappingTabPage(this, fWorkingValues));
// addTabPage(fTabFolder, FormatterMessages.ModifyDialog_tabpage_comments_title, new CommentsTabPage(this, fWorkingValues));
applyDialogFont(composite);
// fTabFolder.addSelectionListener(new SelectionListener() {
// public void widgetDefaultSelected(SelectionEvent e) {}
// public void widgetSelected(SelectionEvent e) {
// final TabItem tabItem= (TabItem)e.item;
// final ModifyDialogTabPage page= (ModifyDialogTabPage)tabItem.getData();
//// page.fSashForm.setWeights();
// fDialogSettings.put(DS_KEY_LAST_FOCUS, fTabPages.indexOf(page));
// page.makeVisible();
// }
// });
return composite;
}
public void updateStatus(IStatus status) {
super.updateStatus(status != null ? status : fStandardStatus);
}
/* (non-Javadoc)
* @see org.eclipse.jface.window.Window#getInitialSize()
*/
protected Point getInitialSize() {
Point initialSize= super.getInitialSize();
try {
int lastWidth= fDialogSettings.getInt(DS_KEY_PREFERRED_WIDTH);
if (initialSize.x > lastWidth)
lastWidth= initialSize.x;
int lastHeight= fDialogSettings.getInt(DS_KEY_PREFERRED_HEIGHT);
if (initialSize.y > lastHeight)
lastHeight= initialSize.x;
return new Point(lastWidth, lastHeight);
} catch (NumberFormatException ex) {
}
return initialSize;
}
/* (non-Javadoc)
* @see org.eclipse.jface.window.Window#getInitialLocation(org.eclipse.swt.graphics.Point)
*/
protected Point getInitialLocation(Point initialSize) {
try {
return new Point(fDialogSettings.getInt(DS_KEY_PREFERRED_X), fDialogSettings.getInt(DS_KEY_PREFERRED_Y));
} catch (NumberFormatException ex) {
return super.getInitialLocation(initialSize);
}
}
public boolean close() {
final Rectangle shell= getShell().getBounds();
fDialogSettings.put(DS_KEY_PREFERRED_WIDTH, shell.width);
fDialogSettings.put(DS_KEY_PREFERRED_HEIGHT, shell.height);
fDialogSettings.put(DS_KEY_PREFERRED_X, shell.x);
fDialogSettings.put(DS_KEY_PREFERRED_Y, shell.y);
return super.close();
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.Dialog#okPressed()
*/
protected void okPressed() {
applyPressed();
super.okPressed();
}
protected void buttonPressed(int buttonId) {
if (buttonId == IDialogConstants.CLIENT_ID) {
applyPressed();
} else {
super.buttonPressed(buttonId);
}
}
private void applyPressed() {
if (fProfile.isBuiltInProfile() || fProfile.isSharedProfile()) {
RenameProfileDialog dialog= new RenameProfileDialog(getShell(), fProfile, fProfileManager);
if (dialog.open() != Window.OK) {
return;
}
fProfile= dialog.getRenamedProfile();
fStandardStatus= new Status(IStatus.OK, CUIPlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$
updateStatus(fStandardStatus);
}
fProfile.setSettings(new HashMap(fWorkingValues));
// fApplyButton.setEnabled(false);
}
protected void createButtonsForButtonBar(Composite parent) {
// fApplyButton= createButton(parent, IDialogConstants.CLIENT_ID, FormatterMessages.ModifyDialog_apply_button, false);
// fApplyButton.setEnabled(false);
GridLayout layout= (GridLayout) parent.getLayout();
layout.numColumns++;
layout.makeColumnsEqualWidth= false;
Label label= new Label(parent, SWT.NONE);
GridData data= new GridData();
data.widthHint= layout.horizontalSpacing;
label.setLayoutData(data);
super.createButtonsForButtonBar(parent);
}
// private final void addTabPage(TabFolder tabFolder, String title, ModifyDialogTabPage tabPage) {
// final TabItem tabItem= new TabItem(tabFolder, SWT.NONE);
// applyDialogFont(tabItem.getControl());
// tabItem.setText(title);
// tabItem.setData(tabPage);
// tabItem.setControl(tabPage.createContents(tabFolder));
// fTabPages.add(tabPage);
// }
public void valuesModified() {
// if (fApplyButton != null && !fApplyButton.isDisposed()) {
// fApplyButton.setEnabled(hasChanges());
// }
}
// private boolean hasChanges() {
// Iterator iter= fProfile.getSettings().entrySet().iterator();
// for (;iter.hasNext();) {
// Map.Entry curr= (Map.Entry) iter.next();
// if (!fWorkingValues.get(curr.getKey()).equals(curr.getValue())) {
// return true;
// }
// }
// return false;
// }
}

View file

@ -0,0 +1,802 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences.formatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
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.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.ui.util.Messages;
import org.eclipse.cdt.internal.ui.util.PixelConverter;
public abstract class ModifyDialogTabPage {
/**
* This is the default listener for any of the Preference
* classes. It is added by the respective factory methods and
* updates the page's preview on each change.
*/
protected final Observer fUpdater= new Observer() {
public void update(Observable o, Object arg) {
doUpdatePreview();
notifyValuesModified();
}
};
/**
* The base class of all Preference classes. A preference class provides a wrapper
* around one or more SWT widgets and handles the input of values for some key.
* On each change, the new value is written to the map and the listeners are notified.
*/
protected abstract class Preference extends Observable {
private final Map fPreferences;
private boolean fEnabled;
private String fKey;
/**
* Create a new Preference.
* @param preferences The map where the value is written.
* @param key The key for which a value is managed.
*/
public Preference(Map preferences, String key) {
fPreferences= preferences;
fEnabled= true;
fKey= key;
}
/**
* @return Gets the map of this Preference.
*/
protected final Map getPreferences() {
return fPreferences;
}
/**
* Set the enabled state of all SWT widgets of this preference.
* @param enabled new value
*/
public final void setEnabled(boolean enabled) {
fEnabled= enabled;
updateWidget();
}
/**
* @return Gets the enabled state of all SWT widgets of this Preference.
*/
public final boolean getEnabled() {
return fEnabled;
}
/**
* Set the key which is used to store the value.
* @param key New value
*/
public final void setKey(String key) {
if (key == null || !fKey.equals(key)) {
fKey= key;
updateWidget();
}
}
/**
* @return Gets the currently used key which is used to store the value.
*/
public final String getKey() {
return fKey;
}
/**
* Returns the main control of a preference, which is mainly used to
* manage the focus. This may be <code>null</code> if the preference doesn't
* have a control which is able to have the focus.
* @return The main control
*/
public abstract Control getControl();
/**
* To be implemented in subclasses. Update the SWT widgets when the state
* of this object has changed (enabled, key, ...).
*/
protected abstract void updateWidget();
}
/**
* Wrapper around a checkbox and a label.
*/
protected final class CheckboxPreference extends Preference {
private final String[] fValues;
private final Button fCheckbox;
/**
* Create a new CheckboxPreference.
* @param composite The composite on which the SWT widgets are added.
* @param numColumns The number of columns in the composite's GridLayout.
* @param preferences The map to store the values.
* @param key The key to store the values.
* @param values An array of two elements indicating the values to store on unchecked/checked.
* @param text The label text for this Preference.
*/
public CheckboxPreference(Composite composite, int numColumns,
Map preferences, String key,
String [] values, String text) {
super(preferences, key);
if (values == null || text == null)
throw new IllegalArgumentException(FormatterMessages.ModifyDialogTabPage_error_msg_values_text_unassigned);
fValues= values;
fCheckbox= new Button(composite, SWT.CHECK);
fCheckbox.setText(text);
fCheckbox.setLayoutData(createGridData(numColumns, GridData.FILL_HORIZONTAL, SWT.DEFAULT));
fCheckbox.setFont(composite.getFont());
updateWidget();
fCheckbox.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
checkboxChecked(((Button)e.widget).getSelection());
}
});
}
protected void checkboxChecked(boolean state) {
getPreferences().put(getKey(), state ? fValues[1] : fValues[0]);
setChanged();
notifyObservers();
}
protected void updateWidget() {
if (getKey() != null) {
fCheckbox.setEnabled(getEnabled());
fCheckbox.setSelection(getChecked());
} else {
fCheckbox.setSelection(false);
fCheckbox.setEnabled(false);
}
}
public boolean getChecked() {
return fValues[1].equals(getPreferences().get(getKey()));
}
public Control getControl() {
return fCheckbox;
}
}
/**
* Wrapper around a Combo box.
*/
protected final class ComboPreference extends Preference {
private final String [] fItems;
private final String[] fValues;
private final Combo fCombo;
/**
* Create a new ComboPreference.
* @param composite The composite on which the SWT widgets are added.
* @param numColumns The number of columns in the composite's GridLayout.
* @param preferences The map to store the values.
* @param key The key to store the values.
* @param values An array of n elements indicating the values to store for each selection.
* @param text The label text for this Preference.
* @param items An array of n elements indicating the text to be written in the combo box.
*/
public ComboPreference(Composite composite, int numColumns,
Map preferences, String key,
String [] values, String text, String [] items) {
super(preferences, key);
if (values == null || items == null || text == null)
throw new IllegalArgumentException(FormatterMessages.ModifyDialogTabPage_error_msg_values_items_text_unassigned);
fValues= values;
fItems= items;
createLabel(numColumns - 1, composite, text);
fCombo= new Combo(composite, SWT.SINGLE | SWT.READ_ONLY);
fCombo.setFont(composite.getFont());
fCombo.setItems(items);
int max= 0;
for (int i= 0; i < items.length; i++)
if (items[i].length() > max) max= items[i].length();
fCombo.setLayoutData(createGridData(1, GridData.HORIZONTAL_ALIGN_FILL, fCombo.computeSize(SWT.DEFAULT, SWT.DEFAULT).x));
updateWidget();
fCombo.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
comboSelected(((Combo)e.widget).getSelectionIndex());
}
});
}
protected void comboSelected(int index) {
getPreferences().put(getKey(), fValues[index]);
setChanged();
notifyObservers(fValues[index]);
}
protected void updateWidget() {
if (getKey() != null) {
fCombo.setEnabled(getEnabled());
fCombo.setText(getSelectedItem());
} else {
fCombo.setText(""); //$NON-NLS-1$
fCombo.setEnabled(false);
}
}
public String getSelectedItem() {
final String selected= (String)getPreferences().get(getKey());
for (int i= 0; i < fValues.length; i++) {
if (fValues[i].equals(selected)) {
return fItems[i];
}
}
return ""; //$NON-NLS-1$
}
public boolean hasValue(String value) {
return value.equals(getPreferences().get(getKey()));
}
public Control getControl() {
return fCombo;
}
}
/**
* Wrapper around a textfied which requests an integer input of a given range.
*/
protected final class NumberPreference extends Preference {
private final int fMinValue, fMaxValue;
private final Label fNumberLabel;
private final Text fNumberText;
protected int fSelected;
protected int fOldSelected;
/**
* Create a new NumberPreference.
* @param composite The composite on which the SWT widgets are added.
* @param numColumns The number of columns in the composite's GridLayout.
* @param preferences The map to store the values.
* @param key The key to store the values.
* @param minValue The minimum value which is valid input.
* @param maxValue The maximum value which is valid input.
* @param text The label text for this Preference.
*/
public NumberPreference(Composite composite, int numColumns,
Map preferences, String key,
int minValue, int maxValue, String text) {
super(preferences, key);
fNumberLabel= createLabel(numColumns - 1, composite, text, GridData.FILL_HORIZONTAL);
fNumberText= new Text(composite, SWT.SINGLE | SWT.BORDER | SWT.RIGHT);
fNumberText.setFont(composite.getFont());
final int length= Integer.toString(maxValue).length() + 3;
fNumberText.setLayoutData(createGridData(1, GridData.HORIZONTAL_ALIGN_END, fPixelConverter.convertWidthInCharsToPixels(length)));
fMinValue= minValue;
fMaxValue= maxValue;
updateWidget();
fNumberText.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
NumberPreference.this.focusGained();
}
public void focusLost(FocusEvent e) {
NumberPreference.this.focusLost();
}
});
fNumberText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
fieldModified();
}
});
}
private IStatus createErrorStatus() {
return new Status(IStatus.ERROR, CUIPlugin.getPluginId(), 0, Messages.format(FormatterMessages.ModifyDialogTabPage_NumberPreference_error_invalid_value, new String [] {Integer.toString(fMinValue), Integer.toString(fMaxValue)}), null);
}
protected void focusGained() {
fOldSelected= fSelected;
fNumberText.setSelection(0, fNumberText.getCharCount());
}
protected void focusLost() {
updateStatus(null);
final String input= fNumberText.getText();
if (!validInput(input))
fSelected= fOldSelected;
else
fSelected= Integer.parseInt(input);
if (fSelected != fOldSelected) {
saveSelected();
fNumberText.setText(Integer.toString(fSelected));
}
}
protected void fieldModified() {
final String trimInput= fNumberText.getText().trim();
final boolean valid= validInput(trimInput);
updateStatus(valid ? null : createErrorStatus());
if (valid) {
final int number= Integer.parseInt(trimInput);
if (fSelected != number) {
fSelected= number;
saveSelected();
}
}
}
private boolean validInput(String trimInput) {
int number;
try {
number= Integer.parseInt(trimInput);
} catch (NumberFormatException x) {
return false;
}
if (number < fMinValue) return false;
if (number > fMaxValue) return false;
return true;
}
private void saveSelected() {
getPreferences().put(getKey(), Integer.toString(fSelected));
setChanged();
notifyObservers();
}
protected void updateWidget() {
final boolean hasKey= getKey() != null;
fNumberLabel.setEnabled(hasKey && getEnabled());
fNumberText.setEnabled(hasKey && getEnabled());
if (hasKey) {
String s= (String)getPreferences().get(getKey());
try {
fSelected= Integer.parseInt(s);
} catch (NumberFormatException e) {
final String message= Messages.format(FormatterMessages.ModifyDialogTabPage_NumberPreference_error_invalid_key, getKey());
CUIPlugin.getDefault().log(new Status(IStatus.ERROR, CUIPlugin.getPluginId(), IStatus.OK, message, e));
s= ""; //$NON-NLS-1$
}
fNumberText.setText(s);
} else {
fNumberText.setText(""); //$NON-NLS-1$
}
}
public Control getControl() {
return fNumberText;
}
}
/**
* This class provides the default way to preserve and re-establish the focus
* over multiple modify sessions. Each ModifyDialogTabPage has its own instance,
* and it should add all relevant controls upon creation, always in the same sequence.
* This established a mapping of controls to indexes, which allows to restore the focus
* in a later session.
* The index is saved in the dialog settings, and there is only one common preference for
* all tab pages. It is always the currently active tab page which stores its focus
* index.
*/
protected final static class DefaultFocusManager extends FocusAdapter {
private final static String PREF_LAST_FOCUS_INDEX= CUIPlugin.PLUGIN_ID + "formatter_page.modify_dialog_tab_page.last_focus_index"; //$NON-NLS-1$
private final IDialogSettings fDialogSettings;
private final Map fItemMap;
private final List fItemList;
private int fIndex;
public DefaultFocusManager() {
fDialogSettings= CUIPlugin.getDefault().getDialogSettings();
fItemMap= new HashMap();
fItemList= new ArrayList();
fIndex= 0;
}
public void focusGained(FocusEvent e) {
fDialogSettings.put(PREF_LAST_FOCUS_INDEX, ((Integer)fItemMap.get(e.widget)).intValue());
}
public void add(Control control) {
control.addFocusListener(this);
fItemList.add(fIndex, control);
fItemMap.put(control, new Integer(fIndex++));
}
public void add(Preference preference) {
final Control control= preference.getControl();
if (control != null)
add(control);
}
public boolean isUsed() {
return fIndex != 0;
}
public void restoreFocus() {
int index= 0;
try {
index= fDialogSettings.getInt(PREF_LAST_FOCUS_INDEX);
// make sure the value is within the range
if ((index >= 0) && (index <= fItemList.size() - 1)) {
((Control)fItemList.get(index)).setFocus();
}
} catch (NumberFormatException ex) {
// this is the first time
}
}
public void resetFocus() {
fDialogSettings.put(PREF_LAST_FOCUS_INDEX, -1);
}
}
/**
* The default focus manager. This widget knows all widgets which can have the focus
* and listens for focusGained events, on which it stores the index of the current
* focus holder. When the dialog is restarted, <code>restoreFocus()</code> sets the
* focus to the last control which had it.
*
* The standard Preference object are managed by this focus manager if they are created
* using the respective factory methods. Other SWT widgets can be added in subclasses
* when they are created.
*/
protected final DefaultFocusManager fDefaultFocusManager;
/**
* Constant array for boolean selection
*/
protected static String[] FALSE_TRUE = {
DefaultCodeFormatterConstants.FALSE,
DefaultCodeFormatterConstants.TRUE
};
/**
* Constant array for insert / not_insert.
*/
protected static String[] DO_NOT_INSERT_INSERT = {
CCorePlugin.DO_NOT_INSERT,
CCorePlugin.INSERT
};
/**
* A pixel converter for layout calculations
*/
protected PixelConverter fPixelConverter;
/**
* The map where the current settings are stored.
*/
protected final Map fWorkingValues;
/**
* The modify dialog where we can display status messages.
*/
private final ModifyDialog fModifyDialog;
/*
* Create a new <code>ModifyDialogTabPage</code>
*/
public ModifyDialogTabPage(ModifyDialog modifyDialog, Map workingValues) {
fWorkingValues= workingValues;
fModifyDialog= modifyDialog;
fDefaultFocusManager= new DefaultFocusManager();
}
/**
* Create the contents of this tab page. Subclasses cannot override this,
* instead they must implement <code>doCreatePreferences</code>. <code>doCreatePreview</code> may also
* be overridden as necessary.
* @param parent The parent composite
* @return Created content control
*/
public final Composite createContents(Composite parent) {
final int numColumns= 4;
if (fPixelConverter == null) {
fPixelConverter= new PixelConverter(parent);
}
// final SashForm fSashForm = new SashForm(parent, SWT.HORIZONTAL);
// fSashForm.setFont(parent.getFont());
// final Composite settingsPane= new Composite(fSashForm, SWT.NONE);
// settingsPane.setFont(fSashForm.getFont());
final Composite settingsPane= new Composite(parent, SWT.NONE);
settingsPane.setFont(parent.getFont());
settingsPane.setLayoutData(new GridData(GridData.FILL_BOTH));
final GridLayout layout= new GridLayout(numColumns, false);
layout.verticalSpacing= (int)(1.5 * fPixelConverter.convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING));
layout.horizontalSpacing= fPixelConverter.convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
layout.marginHeight= fPixelConverter.convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
layout.marginWidth= fPixelConverter.convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
settingsPane.setLayout(layout);
doCreatePreferences(settingsPane, numColumns);
return settingsPane;
// final Composite previewPane= new Composite(fSashForm, SWT.NONE);
// previewPane.setLayout(createGridLayout(numColumns, true));
// previewPane.setFont(fSashForm.getFont());
// doCreatePreviewPane(previewPane, numColumns);
//
// initializePage();
//
// fSashForm.setWeights(new int [] {3, 3});
// return fSashForm;
}
/**
* This method is called after all controls have been alloated, including the preview.
* It can be used to set the preview text and to create listeners.
*
*/
protected abstract void initializePage();
/**
* Create the left side of the modify dialog. This is meant to be implemented by subclasses.
* @param composite Composite to create in
* @param numColumns Number of columns to use
*/
protected abstract void doCreatePreferences(Composite composite, int numColumns);
/**
* Create the right side of the modify dialog. By default, the preview is displayed there.
* Subclasses can override this method in order to customize the right-hand side of the
* dialog.
* @param composite Composite to create in
* @param numColumns Number of columns to use
* @return Created composite
*/
protected Composite doCreatePreviewPane(Composite composite, int numColumns) {
createLabel(numColumns, composite, FormatterMessages.ModifyDialogTabPage_preview_label_text);
final CPreview preview= doCreateCPreview(composite);
fDefaultFocusManager.add(preview.getControl());
final GridData gd= createGridData(numColumns, GridData.FILL_BOTH, 0);
gd.widthHint= 0;
gd.heightHint=0;
preview.getControl().setLayoutData(gd);
return composite;
}
/**
* To be implemented by subclasses. This method should return an instance of CPreview.
* Currently, the choice is between CompilationUnitPreview which contains a valid compilation
* unit, or a SnippetPreview which formats several independent code snippets and displays them
* in the same window.
* @param parent Parent composite
* @return Created preview
*/
protected abstract CPreview doCreateCPreview(Composite parent);
/**
* This is called when the page becomes visible.
* Common tasks to do include:
* <ul><li>Updating the preview.</li>
* <li>Setting the focus</li>
* </ul>
*/
final public void makeVisible() {
fDefaultFocusManager.resetFocus();
doUpdatePreview();
}
/**
* Update the preview. To be implemented by subclasses.
*/
protected abstract void doUpdatePreview();
protected void notifyValuesModified() {
fModifyDialog.valuesModified();
}
/**
* Each tab page should remember where its last focus was, and reset it
* correctly within this method. This method is only called after
* initialization on the first tab page to be displayed in order to restore
* the focus of the last session.
*/
public void setInitialFocus() {
if (fDefaultFocusManager.isUsed()) {
fDefaultFocusManager.restoreFocus();
}
}
/**
* Set the status field on the dialog. This can be used by tab pages to report
* inconsistent input. The OK button is disabled if the kind is IStatus.ERROR.
* @param status Status describing the current page error state
*/
protected void updateStatus(IStatus status) {
fModifyDialog.updateStatus(status);
}
/*
* Factory methods to make GUI construction easier
*/
/*
* Create a GridLayout with the default margin and spacing settings, as
* well as the specified number of columns.
*/
protected GridLayout createGridLayout(int numColumns, boolean margins) {
final GridLayout layout= new GridLayout(numColumns, false);
layout.verticalSpacing= fPixelConverter.convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
layout.horizontalSpacing= fPixelConverter.convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
if (margins) {
layout.marginHeight= fPixelConverter.convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
layout.marginWidth= fPixelConverter.convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
} else {
layout.marginHeight= 0;
layout.marginWidth= 0;
}
return layout;
}
/*
* Convenience method to create a GridData.
*/
protected static GridData createGridData(int numColumns, int style, int widthHint) {
final GridData gd= new GridData(style);
gd.horizontalSpan= numColumns;
gd.widthHint= widthHint;
return gd;
}
/*
* Convenience method to create a label.
*/
protected static Label createLabel(int numColumns, Composite parent, String text) {
return createLabel(numColumns, parent, text, GridData.FILL_HORIZONTAL);
}
/*
* Convenience method to create a label
*/
protected static Label createLabel(int numColumns, Composite parent, String text, int gridDataStyle) {
final Label label= new Label(parent, SWT.WRAP);
label.setFont(parent.getFont());
label.setText(text);
label.setLayoutData(createGridData(numColumns, gridDataStyle, SWT.DEFAULT));
return label;
}
/*
* Convenience method to create a group
*/
protected Group createGroup(int numColumns, Composite parent, String text ) {
final Group group= new Group(parent, SWT.NONE);
group.setFont(parent.getFont());
group.setLayoutData(createGridData(numColumns, GridData.FILL_HORIZONTAL, SWT.DEFAULT));
final GridLayout layout= new GridLayout(numColumns, false);
layout.verticalSpacing= fPixelConverter.convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
layout.horizontalSpacing= fPixelConverter.convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
layout.marginHeight= fPixelConverter.convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
//layout.marginHeight= fPixelConverter.convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
//layout.marginWidth= fPixelConverter.convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
group.setLayout(layout);//createGridLayout(numColumns, true));
group.setText(text);
return group;
}
/*
* Convenience method to create a NumberPreference. The widget is registered as
* a potential focus holder, and the default updater is added.
*/
protected NumberPreference createNumberPref(Composite composite, int numColumns, String name, String key,
int minValue, int maxValue) {
final NumberPreference pref= new NumberPreference(composite, numColumns, fWorkingValues,
key, minValue, maxValue, name);
fDefaultFocusManager.add(pref);
pref.addObserver(fUpdater);
return pref;
}
/*
* Convenience method to create a ComboPreference. The widget is registered as
* a potential focus holder, and the default updater is added.
*/
protected ComboPreference createComboPref(Composite composite, int numColumns, String name,
String key, String [] values, String [] items) {
final ComboPreference pref= new ComboPreference(composite, numColumns,
fWorkingValues, key, values, name, items);
fDefaultFocusManager.add(pref);
pref.addObserver(fUpdater);
return pref;
}
/*
* Convenience method to create a CheckboxPreference. The widget is registered as
* a potential focus holder, and the default updater is added.
*/
protected CheckboxPreference createCheckboxPref(Composite composite, int numColumns, String name, String key,
String [] values) {
final CheckboxPreference pref= new CheckboxPreference(composite, numColumns,
fWorkingValues, key, values, name);
fDefaultFocusManager.add(pref);
pref.addObserver(fUpdater);
return pref;
}
/*
* Create a nice javadoc comment for some string.
*/
protected static String createPreviewHeader(String title) {
return "/**\n* " + title + "\n*/\n"; //$NON-NLS-1$ //$NON-NLS-2$
}
}

View file

@ -0,0 +1,793 @@
/*******************************************************************************
* Copyright (c) 2000, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences.formatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import org.eclipse.core.runtime.preferences.DefaultScope;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.IScopeContext;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ProjectScope;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.cdt.internal.ui.util.Messages;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.ui.PreferenceConstants;
import org.eclipse.cdt.internal.ui.preferences.PreferencesAccess;
import org.osgi.service.prefs.BackingStoreException;
/**
* The model for the set of profiles which are available in the workbench.
*/
public class ProfileManager extends Observable {
/**
* A prefix which is prepended to every ID of a user-defined profile, in order
* to differentiate it from a built-in profile.
*/
private final static String ID_PREFIX= "_"; //$NON-NLS-1$
/**
* Represents a profile with a unique ID, a name and a map
* containing the code formatter settings.
*/
public static abstract class Profile implements Comparable {
public abstract String getName();
public abstract Profile rename(String name, ProfileManager manager);
public abstract Map getSettings();
public abstract void setSettings(Map settings);
public int getVersion() {
return ProfileVersioner.CURRENT_VERSION;
}
public boolean hasEqualSettings(Map otherMap, List allKeys) {
Map settings= getSettings();
for (Iterator iter= allKeys.iterator(); iter.hasNext(); ){
String key= (String) iter.next();
Object other= otherMap.get(key);
Object curr= settings.get(key);
if (other == null) {
if (curr != null) {
return false;
}
} else if (!other.equals(curr)) {
return false;
}
}
return true;
}
public abstract boolean isProfileToSave();
public abstract String getID();
public boolean isSharedProfile() {
return false;
}
public boolean isBuiltInProfile() {
return false;
}
}
/**
* Represents a built-in profile. The state of a built-in profile
* cannot be changed after instantiation.
*/
public final static class BuiltInProfile extends Profile {
private final String fName;
private final String fID;
private final Map fSettings;
private final int fOrder;
protected BuiltInProfile(String ID, String name, Map settings, int order) {
fName= name;
fID= ID;
fSettings= settings;
fOrder= order;
}
public String getName() {
return fName;
}
public Profile rename(String name, ProfileManager manager) {
final String trimmed= name.trim();
CustomProfile newProfile= new CustomProfile(trimmed, fSettings, ProfileVersioner.CURRENT_VERSION);
manager.addProfile(newProfile);
return newProfile;
}
public Map getSettings() {
return fSettings;
}
public void setSettings(Map settings) {
}
public String getID() {
return fID;
}
public final int compareTo(Object o) {
if (o instanceof BuiltInProfile) {
return fOrder - ((BuiltInProfile)o).fOrder;
}
return -1;
}
public boolean isProfileToSave() {
return false;
}
public boolean isBuiltInProfile() {
return true;
}
}
/**
* Represents a user-defined profile. A custom profile can be modified after instantiation.
*/
public static class CustomProfile extends Profile {
private String fName;
private Map fSettings;
protected ProfileManager fManager;
private int fVersion;
public CustomProfile(String name, Map settings, int version) {
fName= name;
fSettings= settings;
fVersion= version;
}
public String getName() {
return fName;
}
public Profile rename(String name, ProfileManager manager) {
final String trimmed= name.trim();
if (trimmed.equals(getName()))
return this;
String oldID= getID(); // remember old id before changing name
fName= trimmed;
manager.profileRenamed(this, oldID);
return this;
}
public Map getSettings() {
return fSettings;
}
public void setSettings(Map settings) {
if (settings == null)
throw new IllegalArgumentException();
fSettings= settings;
if (fManager != null) {
fManager.profileChanged(this);
}
}
public String getID() {
return ID_PREFIX + fName;
}
public void setManager(ProfileManager profileManager) {
fManager= profileManager;
}
public ProfileManager getManager() {
return fManager;
}
public int getVersion() {
return fVersion;
}
public void setVersion(int version) {
fVersion= version;
}
public int compareTo(Object o) {
if (o instanceof SharedProfile) {
return -1;
}
if (o instanceof CustomProfile) {
return getName().compareToIgnoreCase(((Profile)o).getName());
}
return 1;
}
public boolean isProfileToSave() {
return true;
}
}
public final static class SharedProfile extends CustomProfile {
public SharedProfile(String oldName, Map options) {
super(oldName, options, ProfileVersioner.CURRENT_VERSION);
}
public Profile rename(String name, ProfileManager manager) {
CustomProfile profile= new CustomProfile(name.trim(), getSettings(), getVersion());
manager.profileReplaced(this, profile);
return profile;
}
public String getID() {
return SHARED_PROFILE;
}
public final int compareTo(Object o) {
return 1;
}
public boolean isProfileToSave() {
return false;
}
public boolean isSharedProfile() {
return true;
}
}
/**
* The possible events for observers listening to this class.
*/
public final static int SELECTION_CHANGED_EVENT= 1;
public final static int PROFILE_DELETED_EVENT= 2;
public final static int PROFILE_RENAMED_EVENT= 3;
public final static int PROFILE_CREATED_EVENT= 4;
public final static int SETTINGS_CHANGED_EVENT= 5;
/**
* The key of the preference where the selected profile is stored.
*/
private final static String PROFILE_KEY= PreferenceConstants.FORMATTER_PROFILE;
/**
* The key of the preference where the version of the current settings is stored
*/
private final static String FORMATTER_SETTINGS_VERSION= "formatter_settings_version"; //$NON-NLS-1$
/**
* The keys of the built-in profiles
*/
public final static String ECLIPSE_PROFILE= "org.eclipse.cdt.ui.default.eclipse_profile"; //$NON-NLS-1$
public final static String SHARED_PROFILE= "org.eclipse.cdt.ui.default.shared"; //$NON-NLS-1$
public final static String DEFAULT_PROFILE= ECLIPSE_PROFILE;
/**
* A map containing the available profiles, using the IDs as keys.
*/
private final Map fProfiles;
/**
* The available profiles, sorted by name.
*/
private final List fProfilesByName;
/**
* The currently selected profile.
*/
private Profile fSelected;
/**
* The keys of the options to be saved with each profile
*/
private final static List fUIKeys= Collections.EMPTY_LIST;
private final static List fCoreKeys= new ArrayList(DefaultCodeFormatterConstants.getEclipseDefaultSettings().keySet());
/**
* All keys appearing in a profile, sorted alphabetically
*/
private final static List fKeys;
private final PreferencesAccess fPreferencesAccess;
static {
fKeys= new ArrayList();
fKeys.addAll(fUIKeys);
fKeys.addAll(fCoreKeys);
Collections.sort(fKeys);
}
/**
* Create and initialize a new profile manager.
* @param profiles Initial custom profiles (List of type <code>CustomProfile</code>)
*/
public ProfileManager(List profiles, IScopeContext context, PreferencesAccess preferencesAccess) {
fPreferencesAccess= preferencesAccess;
fProfiles= new HashMap();
fProfilesByName= new ArrayList();
addBuiltinProfiles(fProfiles, fProfilesByName);
for (final Iterator iter = profiles.iterator(); iter.hasNext();) {
final CustomProfile profile= (CustomProfile) iter.next();
profile.setManager(this);
fProfiles.put(profile.getID(), profile);
fProfilesByName.add(profile);
}
Collections.sort(fProfilesByName);
IScopeContext instanceScope= fPreferencesAccess.getInstanceScope();
String profileId= instanceScope.getNode(CUIPlugin.PLUGIN_ID).get(PROFILE_KEY, null);
if (profileId == null) {
profileId= new DefaultScope().getNode(CUIPlugin.PLUGIN_ID).get(PROFILE_KEY, null);
}
Profile profile= (Profile) fProfiles.get(profileId);
if (profile == null) {
profile= (Profile) fProfiles.get(DEFAULT_PROFILE);
}
fSelected= profile;
if (context.getName() == ProjectScope.SCOPE && hasProjectSpecificSettings(context)) {
Map map= readFromPreferenceStore(context, profile);
if (map != null) {
Profile matching= null;
String projProfileId= context.getNode(CUIPlugin.PLUGIN_ID).get(PROFILE_KEY, null);
if (projProfileId != null) {
Profile curr= (Profile) fProfiles.get(projProfileId);
if (curr != null && (curr.isBuiltInProfile() || curr.hasEqualSettings(map, getKeys()))) {
matching= curr;
}
} else {
// old version: look for similar
for (final Iterator iter = fProfilesByName.iterator(); iter.hasNext();) {
Profile curr= (Profile) iter.next();
if (curr.hasEqualSettings(map, getKeys())) {
matching= curr;
break;
}
}
}
if (matching == null) {
String name;
if (projProfileId != null && !fProfiles.containsKey(projProfileId)) {
name= Messages.format(FormatterMessages.ProfileManager_unmanaged_profile_with_name, projProfileId.substring(ID_PREFIX.length()));
} else {
name= FormatterMessages.ProfileManager_unmanaged_profile;
}
// current settings do not correspond to any profile -> create a 'team' profile
SharedProfile shared= new SharedProfile(name, map);
shared.setManager(this);
fProfiles.put(shared.getID(), shared);
fProfilesByName.add(shared); // add last
matching= shared;
}
fSelected= matching;
}
}
}
/**
* Notify observers with a message. The message must be one of the following:
* @param message Message to send out
*
* @see #SELECTION_CHANGED_EVENT
* @see #PROFILE_DELETED_EVENT
* @see #PROFILE_RENAMED_EVENT
* @see #PROFILE_CREATED_EVENT
* @see #SETTINGS_CHANGED_EVENT
*/
protected void notifyObservers(int message) {
setChanged();
notifyObservers(new Integer(message));
}
public static boolean hasProjectSpecificSettings(IScopeContext context) {
IEclipsePreferences corePrefs= context.getNode(CCorePlugin.PLUGIN_ID);
for (final Iterator keyIter = fCoreKeys.iterator(); keyIter.hasNext(); ) {
final String key= (String) keyIter.next();
Object val= corePrefs.get(key, null);
if (val != null) {
return true;
}
}
IEclipsePreferences uiPrefs= context.getNode(CUIPlugin.PLUGIN_ID);
for (final Iterator keyIter = fUIKeys.iterator(); keyIter.hasNext(); ) {
final String key= (String) keyIter.next();
Object val= uiPrefs.get(key, null);
if (val != null) {
return true;
}
}
return false;
}
/**
* Only to read project specific settings to find out to what profile it matches.
* @param context The project context
*/
public Map readFromPreferenceStore(IScopeContext context, Profile workspaceProfile) {
final Map profileOptions= new HashMap();
IEclipsePreferences uiPrefs= context.getNode(CUIPlugin.PLUGIN_ID);
IEclipsePreferences corePrefs= context.getNode(CCorePlugin.PLUGIN_ID);
int version= uiPrefs.getInt(FORMATTER_SETTINGS_VERSION, ProfileVersioner.VERSION_1);
if (version != ProfileVersioner.CURRENT_VERSION) {
Map allOptions= new HashMap();
addAll(uiPrefs, allOptions);
addAll(corePrefs, allOptions);
return ProfileVersioner.updateAndComplete(allOptions, version);
}
boolean hasValues= false;
for (final Iterator keyIter = fCoreKeys.iterator(); keyIter.hasNext(); ) {
final String key= (String) keyIter.next();
Object val= corePrefs.get(key, null);
if (val != null) {
hasValues= true;
} else {
val= workspaceProfile.getSettings().get(key);
}
profileOptions.put(key, val);
}
for (final Iterator keyIter = fUIKeys.iterator(); keyIter.hasNext(); ) {
final String key= (String) keyIter.next();
Object val= uiPrefs.get(key, null);
if (val != null) {
hasValues= true;
} else {
val= workspaceProfile.getSettings().get(key);
}
profileOptions.put(key, val);
}
if (!hasValues) {
return null;
}
return profileOptions;
}
/**
* @param uiPrefs
* @param allOptions
*/
private void addAll(IEclipsePreferences uiPrefs, Map allOptions) {
try {
String[] keys= uiPrefs.keys();
for (int i= 0; i < keys.length; i++) {
String key= keys[i];
String val= uiPrefs.get(key, null);
if (val != null) {
allOptions.put(key, val);
}
}
} catch (BackingStoreException e) {
// ignore
}
}
private boolean updatePreferences(IEclipsePreferences prefs, List keys, Map profileOptions) {
boolean hasChanges= false;
for (final Iterator keyIter = keys.iterator(); keyIter.hasNext(); ) {
final String key= (String) keyIter.next();
final String oldVal= prefs.get(key, null);
final String val= (String) profileOptions.get(key);
if (val == null) {
if (oldVal != null) {
prefs.remove(key);
hasChanges= true;
}
} else if (!val.equals(oldVal)) {
prefs.put(key, val);
hasChanges= true;
}
}
return hasChanges;
}
/**
* Update all formatter settings with the settings of the specified profile.
* @param profile The profile to write to the preference store
*/
private void writeToPreferenceStore(Profile profile, IScopeContext context) {
final Map profileOptions= profile.getSettings();
final IEclipsePreferences corePrefs= context.getNode(CCorePlugin.PLUGIN_ID);
updatePreferences(corePrefs, fCoreKeys, profileOptions);
final IEclipsePreferences uiPrefs= context.getNode(CUIPlugin.PLUGIN_ID);
updatePreferences(uiPrefs, fUIKeys, profileOptions);
if (uiPrefs.getInt(FORMATTER_SETTINGS_VERSION, 0) != ProfileVersioner.CURRENT_VERSION) {
uiPrefs.putInt(FORMATTER_SETTINGS_VERSION, ProfileVersioner.CURRENT_VERSION);
}
if (context.getName() == InstanceScope.SCOPE) {
uiPrefs.put(PROFILE_KEY, profile.getID());
} else if (context.getName() == ProjectScope.SCOPE && !profile.isSharedProfile()) {
uiPrefs.put(PROFILE_KEY, profile.getID());
}
}
/**
* Add all the built-in profiles to the map and to the list.
* @param profiles The map to add the profiles to
* @param profilesByName List of profiles by
*/
private void addBuiltinProfiles(Map profiles, List profilesByName) {
final Profile eclipseProfile= new BuiltInProfile(ECLIPSE_PROFILE, FormatterMessages.ProfileManager_default_profile_name, getEclipseSettings(), 2);
profiles.put(eclipseProfile.getID(), eclipseProfile);
profilesByName.add(eclipseProfile);
}
/**
* @return Returns the settings for the new eclipse profile.
*/
public static Map getEclipseSettings() {
return DefaultCodeFormatterConstants.getEclipseDefaultSettings();
}
/**
* @return Returns the default settings.
*/
public static Map getDefaultSettings() {
return getEclipseSettings();
}
/**
* @return All keys appearing in a profile, sorted alphabetically.
*/
public static List getKeys() {
return fKeys;
}
/**
* Get an immutable list as view on all profiles, sorted alphabetically. Unless the set
* of profiles has been modified between the two calls, the sequence is guaranteed to
* correspond to the one returned by <code>getSortedNames</code>.
* @return a list of elements of type <code>Profile</code>
*
* @see #getSortedDisplayNames()
*/
public List getSortedProfiles() {
return Collections.unmodifiableList(fProfilesByName);
}
/**
* Get the names of all profiles stored in this profile manager, sorted alphabetically. Unless the set of
* profiles has been modified between the two calls, the sequence is guaranteed to correspond to the one
* returned by <code>getSortedProfiles</code>.
* @return All names, sorted alphabetically
* @see #getSortedProfiles()
*/
public String[] getSortedDisplayNames() {
final String[] sortedNames= new String[fProfilesByName.size()];
int i= 0;
for (final Iterator iter = fProfilesByName.iterator(); iter.hasNext();) {
Profile curr= (Profile) iter.next();
sortedNames[i++]= curr.getName();
}
return sortedNames;
}
/**
* Get the profile for this profile id.
* @param ID The profile ID
* @return The profile with the given ID or <code>null</code>
*/
public Profile getProfile(String ID) {
return (Profile)fProfiles.get(ID);
}
/**
* Activate the selected profile, update all necessary options in
* preferences and save profiles to disk.
*/
public void commitChanges(IScopeContext scopeContext) {
if (fSelected != null) {
writeToPreferenceStore(fSelected, scopeContext);
}
}
public void clearAllSettings(IScopeContext context) {
final IEclipsePreferences corePrefs= context.getNode(CCorePlugin.PLUGIN_ID);
updatePreferences(corePrefs, fCoreKeys, Collections.EMPTY_MAP);
final IEclipsePreferences uiPrefs= context.getNode(CUIPlugin.PLUGIN_ID);
updatePreferences(uiPrefs, fUIKeys, Collections.EMPTY_MAP);
uiPrefs.remove(PROFILE_KEY);
}
/**
* Get the currently selected profile.
* @return The currently selected profile.
*/
public Profile getSelected() {
return fSelected;
}
/**
* Set the selected profile. The profile must already be contained in this profile manager.
* @param profile The profile to select
*/
public void setSelected(Profile profile) {
final Profile newSelected= (Profile)fProfiles.get(profile.getID());
if (newSelected != null && !newSelected.equals(fSelected)) {
fSelected= newSelected;
notifyObservers(SELECTION_CHANGED_EVENT);
}
}
/**
* Check whether a user-defined profile in this profile manager
* already has this name.
* @param name The name to test for
* @return Returns <code>true</code> if a profile with the given name exists
*/
public boolean containsName(String name) {
for (final Iterator iter = fProfilesByName.iterator(); iter.hasNext();) {
Profile curr= (Profile) iter.next();
if (name.equals(curr.getName())) {
return true;
}
}
return false;
}
/**
* Add a new custom profile to this profile manager.
* @param profile The profile to add
*/
public void addProfile(CustomProfile profile) {
profile.setManager(this);
final CustomProfile oldProfile= (CustomProfile)fProfiles.get(profile.getID());
if (oldProfile != null) {
fProfiles.remove(oldProfile.getID());
fProfilesByName.remove(oldProfile);
oldProfile.setManager(null);
}
fProfiles.put(profile.getID(), profile);
fProfilesByName.add(profile);
Collections.sort(fProfilesByName);
fSelected= profile;
notifyObservers(PROFILE_CREATED_EVENT);
}
/**
* Delete the currently selected profile from this profile manager. The next profile
* in the list is selected.
* @return true if the profile has been successfully removed, false otherwise.
*/
public boolean deleteSelected() {
if (!(fSelected instanceof CustomProfile))
return false;
Profile removedProfile= fSelected;
int index= fProfilesByName.indexOf(removedProfile);
fProfiles.remove(removedProfile.getID());
fProfilesByName.remove(removedProfile);
((CustomProfile)removedProfile).setManager(null);
if (index >= fProfilesByName.size())
index--;
fSelected= (Profile) fProfilesByName.get(index);
if (!removedProfile.isSharedProfile()) {
updateProfilesWithName(removedProfile.getID(), null, false);
}
notifyObservers(PROFILE_DELETED_EVENT);
return true;
}
public void profileRenamed(CustomProfile profile, String oldID) {
fProfiles.remove(oldID);
fProfiles.put(profile.getID(), profile);
if (!profile.isSharedProfile()) {
updateProfilesWithName(oldID, profile, false);
}
Collections.sort(fProfilesByName);
notifyObservers(PROFILE_RENAMED_EVENT);
}
public void profileReplaced(CustomProfile oldProfile, CustomProfile newProfile) {
fProfiles.remove(oldProfile.getID());
fProfiles.put(newProfile.getID(), newProfile);
fProfilesByName.remove(oldProfile);
fProfilesByName.add(newProfile);
Collections.sort(fProfilesByName);
if (!oldProfile.isSharedProfile()) {
updateProfilesWithName(oldProfile.getID(), null, false);
}
setSelected(newProfile);
notifyObservers(PROFILE_CREATED_EVENT);
notifyObservers(SELECTION_CHANGED_EVENT);
}
public void profileChanged(CustomProfile profile) {
if (!profile.isSharedProfile()) {
updateProfilesWithName(profile.getID(), profile, true);
}
notifyObservers(SETTINGS_CHANGED_EVENT);
}
private void updateProfilesWithName(String oldName, Profile newProfile, boolean applySettings) {
IProject[] projects= ResourcesPlugin.getWorkspace().getRoot().getProjects();
for (int i= 0; i < projects.length; i++) {
IScopeContext projectScope= fPreferencesAccess.getProjectScope(projects[i]);
IEclipsePreferences node= projectScope.getNode(CUIPlugin.PLUGIN_ID);
String profileId= node.get(PROFILE_KEY, null);
if (oldName.equals(profileId)) {
if (newProfile == null) {
node.remove(PROFILE_KEY);
} else {
if (applySettings) {
writeToPreferenceStore(newProfile, projectScope);
} else {
node.put(PROFILE_KEY, newProfile.getID());
}
}
}
}
IScopeContext instanceScope= fPreferencesAccess.getInstanceScope();
final IEclipsePreferences uiPrefs= instanceScope.getNode(CUIPlugin.PLUGIN_ID);
if (newProfile != null && oldName.equals(uiPrefs.get(PROFILE_KEY, null))) {
writeToPreferenceStore(newProfile, instanceScope);
}
}
}

View file

@ -0,0 +1,427 @@
/*******************************************************************************
* Copyright (c) 2000, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences.formatter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
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.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.IScopeContext;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.ui.CUIException;
import org.eclipse.cdt.internal.ui.CUIStatus;
import org.eclipse.cdt.internal.ui.preferences.PreferencesAccess;
import org.eclipse.cdt.internal.ui.preferences.formatter.ProfileManager.CustomProfile;
import org.eclipse.cdt.internal.ui.preferences.formatter.ProfileManager.Profile;
import org.osgi.service.prefs.BackingStoreException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class ProfileStore {
/**
* A SAX event handler to parse the xml format for profiles.
*/
private final static class ProfileDefaultHandler extends DefaultHandler {
private List fProfiles;
private int fVersion;
private String fName;
private Map fSettings;
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equals(XML_NODE_SETTING)) {
final String key= attributes.getValue(XML_ATTRIBUTE_ID);
final String value= attributes.getValue(XML_ATTRIBUTE_VALUE);
fSettings.put(key, value);
} else if (qName.equals(XML_NODE_PROFILE)) {
fName= attributes.getValue(XML_ATTRIBUTE_NAME);
fSettings= new HashMap(200);
}
else if (qName.equals(XML_NODE_ROOT)) {
fProfiles= new ArrayList();
try {
fVersion= Integer.parseInt(attributes.getValue(XML_ATTRIBUTE_VERSION));
} catch (NumberFormatException ex) {
throw new SAXException(ex);
}
}
}
public void endElement(String uri, String localName, String qName) {
if (qName.equals(XML_NODE_PROFILE)) {
fProfiles.add(new CustomProfile(fName, fSettings, fVersion));
fName= null;
fSettings= null;
}
}
public List getProfiles() {
return fProfiles;
}
}
/**
* Preference key where all profiles are stored
*/
private static final String PREF_FORMATTER_PROFILES= "org.eclipse.cdt.ui.formatterprofiles"; //$NON-NLS-1$
/**
* Preference key where all profiles are stored
*/
private static final String PREF_FORMATTER_PROFILES_VERSION= "org.eclipse.cdt.ui.formatterprofiles.version"; //$NON-NLS-1$
/**
* Identifiers for the XML file.
*/
private final static String XML_NODE_ROOT= "profiles"; //$NON-NLS-1$
private final static String XML_NODE_PROFILE= "profile"; //$NON-NLS-1$
private final static String XML_NODE_SETTING= "setting"; //$NON-NLS-1$
private final static String XML_ATTRIBUTE_VERSION= "version"; //$NON-NLS-1$
private final static String XML_ATTRIBUTE_ID= "id"; //$NON-NLS-1$
private final static String XML_ATTRIBUTE_NAME= "name"; //$NON-NLS-1$
private final static String XML_ATTRIBUTE_VALUE= "value"; //$NON-NLS-1$
private ProfileStore() {
}
/**
* @return Returns the collection of profiles currently stored in the preference store or
* <code>null</code> if the loading failed. The elements are of type {@link CustomProfile}
* and are all updated to the latest version.
* @throws CoreException
*/
public static List readProfiles(IScopeContext scope) throws CoreException {
List res= readProfilesFromPreferences(scope);
if (res == null) {
return readOldForCompatibility(scope);
}
return res;
}
public static void writeProfiles(Collection profiles, IScopeContext instanceScope) throws CoreException {
ByteArrayOutputStream stream= new ByteArrayOutputStream(2000);
try {
writeProfilesToStream(profiles, stream);
String val;
try {
val= stream.toString("UTF-8"); //$NON-NLS-1$
} catch (UnsupportedEncodingException e) {
val= stream.toString();
}
IEclipsePreferences uiPreferences = instanceScope.getNode(CUIPlugin.PLUGIN_ID);
uiPreferences.put(PREF_FORMATTER_PROFILES, val);
uiPreferences.putInt(PREF_FORMATTER_PROFILES_VERSION, ProfileVersioner.CURRENT_VERSION);
} finally {
try { stream.close(); } catch (IOException e) { /* ignore */ }
}
}
public static List readProfilesFromPreferences(IScopeContext scope) throws CoreException {
String string= scope.getNode(CUIPlugin.PLUGIN_ID).get(PREF_FORMATTER_PROFILES, null);
if (string != null && string.length() > 0) {
byte[] bytes;
try {
bytes= string.getBytes("UTF-8"); //$NON-NLS-1$
} catch (UnsupportedEncodingException e) {
bytes= string.getBytes();
}
InputStream is= new ByteArrayInputStream(bytes);
try {
List res= readProfilesFromStream(new InputSource(is));
if (res != null) {
for (int i= 0; i < res.size(); i++) {
ProfileVersioner.updateAndComplete((CustomProfile) res.get(i));
}
}
return res;
} finally {
try { is.close(); } catch (IOException e) { /* ignore */ }
}
}
return null;
}
/**
* Read the available profiles from the internal XML file and return them
* as collection.
* @return returns a list of <code>CustomProfile</code> or <code>null</code>
*/
private static List readOldForCompatibility(IScopeContext instanceScope) {
// in 3.0 M9 and less the profiles were stored in a file in the plugin's meta data
final String STORE_FILE= "code_formatter_profiles.xml"; //$NON-NLS-1$
File file= CUIPlugin.getDefault().getStateLocation().append(STORE_FILE).toFile();
if (!file.exists())
return null;
try {
// note that it's wrong to use a file reader when XML declares UTF-8: Kept for compatibility
final FileReader reader= new FileReader(file);
try {
List res= readProfilesFromStream(new InputSource(reader));
if (res != null) {
for (int i= 0; i < res.size(); i++) {
ProfileVersioner.updateAndComplete((CustomProfile) res.get(i));
}
writeProfiles(res, instanceScope);
}
file.delete(); // remove after successful write
return res;
} finally {
reader.close();
}
} catch (CoreException e) {
CUIPlugin.getDefault().log(e); // log but ignore
} catch (IOException e) {
CUIPlugin.getDefault().log(e); // log but ignore
}
return null;
}
/**
* Read the available profiles from the internal XML file and return them
* as collection or <code>null</code> if the file is not a profile file.
* @param file The file to read from
* @return returns a list of <code>CustomProfile</code> or <code>null</code>
* @throws CoreException
*/
public static List readProfilesFromFile(File file) throws CoreException {
try {
final FileInputStream reader= new FileInputStream(file);
try {
return readProfilesFromStream(new InputSource(reader));
} finally {
try { reader.close(); } catch (IOException e) { /* ignore */ }
}
} catch (IOException e) {
throw createException(e, FormatterMessages.CodingStyleConfigurationBlock_error_reading_xml_message);
}
}
/**
* Load profiles from a XML stream and add them to a map or <code>null</code> if the source is not a profile store.
* @param inputSource The input stream
* @return returns a list of <code>CustomProfile</code> or <code>null</code>
* @throws CoreException
*/
private static List readProfilesFromStream(InputSource inputSource) throws CoreException {
final ProfileDefaultHandler handler= new ProfileDefaultHandler();
try {
final SAXParserFactory factory= SAXParserFactory.newInstance();
final SAXParser parser= factory.newSAXParser();
parser.parse(inputSource, handler);
} catch (SAXException e) {
throw createException(e, FormatterMessages.CodingStyleConfigurationBlock_error_reading_xml_message);
} catch (IOException e) {
throw createException(e, FormatterMessages.CodingStyleConfigurationBlock_error_reading_xml_message);
} catch (ParserConfigurationException e) {
throw createException(e, FormatterMessages.CodingStyleConfigurationBlock_error_reading_xml_message);
}
return handler.getProfiles();
}
/**
* Write the available profiles to the internal XML file.
* @param profiles List of <code>CustomProfile</code>
* @param file File to write
* @throws CoreException
*/
public static void writeProfilesToFile(Collection profiles, File file) throws CoreException {
final OutputStream writer;
try {
writer= new FileOutputStream(file);
try {
writeProfilesToStream(profiles, writer);
} finally {
try { writer.close(); } catch (IOException e) { /* ignore */ }
}
} catch (IOException e) {
throw createException(e, FormatterMessages.CodingStyleConfigurationBlock_error_serializing_xml_message);
}
}
/**
* Save profiles to an XML stream
* @param profiles List of <code>CustomProfile</code>
* @param stream Stream to write
* @throws CoreException
*/
private static void writeProfilesToStream(Collection profiles, OutputStream stream) throws CoreException {
try {
final DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
final DocumentBuilder builder= factory.newDocumentBuilder();
final Document document= builder.newDocument();
final Element rootElement = document.createElement(XML_NODE_ROOT);
rootElement.setAttribute(XML_ATTRIBUTE_VERSION, Integer.toString(ProfileVersioner.CURRENT_VERSION));
document.appendChild(rootElement);
for(final Iterator iter= profiles.iterator(); iter.hasNext();) {
final Profile profile= (Profile)iter.next();
if (profile.isProfileToSave()) {
final Element profileElement= createProfileElement(profile, document);
rootElement.appendChild(profileElement);
}
}
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$
transformer.transform(new DOMSource(document), new StreamResult(stream));
} catch (TransformerException e) {
throw createException(e, FormatterMessages.CodingStyleConfigurationBlock_error_serializing_xml_message);
} catch (ParserConfigurationException e) {
throw createException(e, FormatterMessages.CodingStyleConfigurationBlock_error_serializing_xml_message);
}
}
/*
* Create a new profile element in the specified document. The profile is not added
* to the document by this method.
*/
private static Element createProfileElement(Profile profile, Document document) {
final Element element= document.createElement(XML_NODE_PROFILE);
element.setAttribute(XML_ATTRIBUTE_NAME, profile.getName());
element.setAttribute(XML_ATTRIBUTE_VERSION, Integer.toString(profile.getVersion()));
final Iterator keyIter= ProfileManager.getKeys().iterator();
while (keyIter.hasNext()) {
final String key= (String)keyIter.next();
final String value= (String)profile.getSettings().get(key);
if (value != null) {
final Element setting= document.createElement(XML_NODE_SETTING);
setting.setAttribute(XML_ATTRIBUTE_ID, key);
setting.setAttribute(XML_ATTRIBUTE_VALUE, value);
element.appendChild(setting);
} else {
CUIPlugin.getDefault().logErrorMessage("ProfileStore: Profile does not contain value for key " + key); //$NON-NLS-1$
}
}
return element;
}
public static void checkCurrentOptionsVersion() {
PreferencesAccess access= PreferencesAccess.getOriginalPreferences();
IScopeContext instanceScope= access.getInstanceScope();
IEclipsePreferences uiPreferences= instanceScope.getNode(CUIPlugin.PLUGIN_ID);
int version= uiPreferences.getInt(PREF_FORMATTER_PROFILES_VERSION, 0);
if (version >= ProfileVersioner.CURRENT_VERSION) {
return; // is up to date
}
try {
List profiles= ProfileStore.readProfiles(instanceScope);
if (profiles == null) {
profiles= Collections.EMPTY_LIST;
}
ProfileManager manager= new ProfileManager(profiles, instanceScope, access);
if (manager.getSelected() instanceof CustomProfile) {
manager.commitChanges(instanceScope); // updates CCorePlugin options
}
uiPreferences.putInt(PREF_FORMATTER_PROFILES_VERSION, ProfileVersioner.CURRENT_VERSION);
savePreferences(instanceScope);
IProject[] projects= ResourcesPlugin.getWorkspace().getRoot().getProjects();
for (int i= 0; i < projects.length; i++) {
IScopeContext scope= access.getProjectScope(projects[i]);
if (ProfileManager.hasProjectSpecificSettings(scope)) {
manager= new ProfileManager(profiles, scope, access);
manager.commitChanges(scope); // updates CCorePlugin project options
savePreferences(scope);
}
}
} catch (CoreException e) {
CUIPlugin.getDefault().log(e);
} catch (BackingStoreException e) {
CUIPlugin.getDefault().log(e);
}
}
private static void savePreferences(final IScopeContext context) throws BackingStoreException {
try {
context.getNode(CUIPlugin.PLUGIN_ID).flush();
} finally {
context.getNode(CCorePlugin.PLUGIN_ID).flush();
}
}
/*
* Creates a UI exception for logging purposes
*/
private static CUIException createException(Throwable t, String message) {
return new CUIException(CUIStatus.createError(IStatus.ERROR, message, t));
}
}

View file

@ -0,0 +1,63 @@
/*******************************************************************************
* Copyright (c) 2000, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences.formatter;
import java.util.Iterator;
import java.util.Map;
import org.eclipse.cdt.internal.ui.preferences.formatter.ProfileManager.CustomProfile;
public class ProfileVersioner {
public static final int VERSION_1= 1; // < 20040113 (includes M6)
public static final int CURRENT_VERSION= VERSION_1;
public static int getVersionStatus(CustomProfile profile) {
final int version= profile.getVersion();
if (version < CURRENT_VERSION)
return -1;
else if (version > CURRENT_VERSION)
return 1;
else
return 0;
}
public static void updateAndComplete(CustomProfile profile) {
final Map oldSettings= profile.getSettings();
Map newSettings= updateAndComplete(oldSettings, profile.getVersion());
profile.setVersion(CURRENT_VERSION);
profile.setSettings(newSettings);
}
public static Map updateAndComplete(Map oldSettings, int version) {
final Map newSettings= ProfileManager.getDefaultSettings();
switch (version) {
default:
for (final Iterator iter= oldSettings.keySet().iterator(); iter.hasNext(); ) {
final String key= (String)iter.next();
if (!newSettings.containsKey(key))
continue;
final String value= (String)oldSettings.get(key);
if (value != null) {
newSettings.put(key, value);
}
}
}
return newSettings;
}
}

View file

@ -0,0 +1,142 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Aaron Luchko, aluchko@redhat.com - 105926 [Formatter] Exporting Unnamed profile fails silently
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences.formatter;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.StatusDialog;
import org.eclipse.cdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.cdt.internal.ui.preferences.formatter.ProfileManager.Profile;
import org.eclipse.cdt.internal.ui.preferences.formatter.ProfileManager.SharedProfile;
/**
* The dialog to rename a new profile.
*/
public class RenameProfileDialog extends StatusDialog {
private Label fNameLabel;
private Text fNameText;
private final StatusInfo fOk;
private final StatusInfo fEmpty;
private final StatusInfo fDuplicate;
private final StatusInfo fNoMessage;
private final Profile fProfile;
private final ProfileManager fManager;
private Profile fRenamedProfile;
public RenameProfileDialog(Shell parentShell, Profile profile, ProfileManager manager) {
super(parentShell);
fManager= manager;
setTitle(FormatterMessages.RenameProfileDialog_dialog_title);
fProfile= profile;
fOk= new StatusInfo();
fDuplicate= new StatusInfo(IStatus.ERROR, FormatterMessages.RenameProfileDialog_status_message_profile_with_this_name_already_exists);
fEmpty= new StatusInfo(IStatus.ERROR, FormatterMessages.RenameProfileDialog_status_message_profile_name_empty);
fNoMessage= new StatusInfo(IStatus.ERROR, new String());
}
public Control createDialogArea(Composite parent) {
final int numColumns= 2;
GridLayout layout= new GridLayout();
layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
layout.marginWidth= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
layout.verticalSpacing= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
layout.numColumns= numColumns;
final Composite composite= new Composite(parent, SWT.NULL);
composite.setLayout(layout);
// Create "Please enter a new name:" label
GridData gd = new GridData();
gd.horizontalSpan = numColumns;
gd.widthHint= convertWidthInCharsToPixels(60);
fNameLabel = new Label(composite, SWT.NONE);
fNameLabel.setText(FormatterMessages.RenameProfileDialog_dialog_label_enter_a_new_name);
fNameLabel.setLayoutData(gd);
// Create text field to enter name
gd = new GridData( GridData.FILL_HORIZONTAL);
gd.horizontalSpan= numColumns;
fNameText= new Text(composite, SWT.SINGLE | SWT.BORDER);
if (fProfile instanceof SharedProfile) {
fNameText.setText(fProfile.getName());
}
fNameText.setSelection(0, fProfile.getName().length());
fNameText.setLayoutData(gd);
fNameText.addModifyListener( new ModifyListener() {
public void modifyText(ModifyEvent e) {
doValidation();
}
});
fNameText.setText(fProfile.getName());
fNameText.selectAll();
applyDialogFont(composite);
return composite;
}
/**
* Validate the current settings.
*/
protected void doValidation() {
final String name= fNameText.getText().trim();
if (name.length() == 0) {
updateStatus(fEmpty);
return;
}
if (name.equals(fProfile.getName())) {
updateStatus(fNoMessage);
return;
}
if (fManager.containsName(name)) {
updateStatus(fDuplicate);
return;
}
updateStatus(fOk);
}
public Profile getRenamedProfile() {
return fRenamedProfile;
}
protected void okPressed() {
if (!getStatus().isOK())
return;
fRenamedProfile= fProfile.rename(fNameText.getText(), fManager);
super.okPressed();
}
}

View file

@ -0,0 +1,79 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences.formatter;
import java.util.Map;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.formatter.FormattingContextProperties;
import org.eclipse.jface.text.formatter.IContentFormatter;
import org.eclipse.jface.text.formatter.IContentFormatterExtension;
import org.eclipse.jface.text.formatter.IFormattingContext;
import org.eclipse.cdt.internal.ui.ICStatusConstants;
import org.eclipse.cdt.internal.ui.text.comment.CommentFormattingContext;
import org.eclipse.cdt.ui.CUIPlugin;
public class TranslationUnitPreview extends CPreview {
private String fPreviewText;
/**
* @param workingValues
* @param parent
*/
public TranslationUnitPreview(Map workingValues, Composite parent) {
super(workingValues, parent);
}
protected void doFormatPreview() {
if (fPreviewText == null) {
fPreviewDocument.set(""); //$NON-NLS-1$
return;
}
fPreviewDocument.set(fPreviewText);
fSourceViewer.setRedraw(false);
final IFormattingContext context = new CommentFormattingContext();
try {
final IContentFormatter formatter = fViewerConfiguration.getContentFormatter(fSourceViewer);
if (formatter instanceof IContentFormatterExtension) {
final IContentFormatterExtension extension = (IContentFormatterExtension) formatter;
context.setProperty(FormattingContextProperties.CONTEXT_PREFERENCES, fWorkingValues);
context.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.valueOf(true));
extension.format(fPreviewDocument, context);
} else
formatter.format(fPreviewDocument, new Region(0, fPreviewDocument.getLength()));
} catch (Exception e) {
final IStatus status= new Status(IStatus.ERROR, CUIPlugin.getPluginId(), ICStatusConstants.INTERNAL_ERROR,
FormatterMessages.CPreview_formatter_exception, e);
CUIPlugin.getDefault().log(status);
} finally {
context.dispose();
fSourceViewer.setRedraw(true);
}
}
public void setPreviewText(String previewText) {
// if (previewText == null) throw new IllegalArgumentException();
fPreviewText= previewText;
update();
}
}

View file

@ -13,13 +13,18 @@
*******************************************************************************/
package org.eclipse.cdt.internal.ui.text;
import org.eclipse.core.runtime.Assert;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultIndentLineAutoEditStrategy;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.DocumentCommand;
import org.eclipse.jface.text.DocumentRewriteSession;
import org.eclipse.jface.text.DocumentRewriteSessionType;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.jface.text.rules.FastPartitioner;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.texteditor.ITextEditorExtension3;
@ -29,11 +34,15 @@ import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.ui.PreferenceConstants;
import org.eclipse.cdt.ui.text.ICPartitions;
import org.eclipse.cdt.internal.corext.util.CodeFormatterUtil;
/**
* Auto indent strategy sensitive to brackets.
*/
public class CAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy {
private static final String MULTILINE_COMMENT_CLOSE = "*/"; //$NON-NLS-1$
/** The line comment introducer. Value is "{@value}" */
private static final String LINE_COMMENT= "//"; //$NON-NLS-1$
// private static final GCCScannerExtensionConfiguration C_GNU_SCANNER_EXTENSION = new GCCScannerExtensionConfiguration();
private static class CompilationUnitInfo {
@ -65,12 +74,9 @@ public class CAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy {
// evaluate the line with the opening bracket that matches the closing bracket on the given line
protected int findMatchingOpenBracket(IDocument d, int line, int end, int closingBracketIncrease) throws BadLocationException {
int start = d.getLineOffset(line);
int brackcount = getBracketCount(d, start, end, false) - closingBracketIncrease;
// sum up the brackets counts of each line (closing brackets count negative,
// opening positive) until we find a line the brings the count to zero
while (brackcount < 0) {
@ -85,7 +91,6 @@ public class CAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy {
return line;
}
private int getBracketCount(IDocument d, int start, int end, boolean ignoreCloseBrackets) throws BadLocationException {
int bracketcount = 0;
while (start < end) {
@ -135,7 +140,6 @@ public class CAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy {
// ----------- bracket counting ------------------------------------------------------
private int getCommentEnd(IDocument d, int pos, int end) throws BadLocationException {
while (pos < end) {
char curr = d.getChar(pos);
@ -183,7 +187,6 @@ public class CAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy {
int start = d.getLineOffset(line);
int whiteend = findEndOfWhiteSpace(d, start, c.offset);
// shift only when line does not contain any text up to the closing bracket
if (whiteend == c.offset) {
// evaluate the line with the opening bracket that matches out closing bracket
@ -221,7 +224,7 @@ public class CAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy {
// shift only when line does not contain any text up to the closing bracket
if (whiteend == c.offset) {
// evaluate the line with the opening bracket that matches out closing bracket
int reference = indenter.findReferencePosition(c.offset, false, true, false, false);
int reference = indenter.findReferencePosition(c.offset, false, true, false, false, false);
int indLine = d.getLineOfOffset(reference);
if (indLine != -1 && indLine != line) {
// take the indent of the found line
@ -257,13 +260,13 @@ public class CAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy {
if (d.get(lineOffset, p - lineOffset).trim().length() != 0)
return;
// line of last javacode
// Line of last C code
int pos = scanner.findNonWhitespaceBackward(p, CHeuristicScanner.UNBOUND);
if (pos == -1)
return;
int lastLine = d.getLineOfOffset(pos);
// only shift if the last java line is further up and is a braceless block candidate
// Only shift if the last C line is further up and is a braceless block candidate
if (lastLine < line) {
CIndenter indenter = new CIndenter(d, scanner, fProject);
StringBuffer indent = indenter.computeIndentation(p, true);
@ -405,7 +408,7 @@ public class CAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy {
* Finds a closing parenthesis to the left of <code>position</code> in document, where that parenthesis is only
* separated by whitespace from <code>position</code>. If no such parenthesis can be found, <code>position</code> is returned.
*
* @param scanner the java heuristic scanner set up on the document
* @param scanner the C heuristic scanner set up on the document
* @param position the first character position in <code>document</code> to be considered
* @return the position of a closing parenthesis left to <code>position</code> separated only by whitespace, or <code>position</code> if no parenthesis can be found
*/
@ -519,6 +522,448 @@ public class CAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy {
return false;
}
/**
* Installs a C partitioner with <code>document</code>.
*
* @param document the document
*/
private static void installCPartitioner(Document document) {
String[] types= new String[] {
ICPartitions.C_MULTI_LINE_COMMENT,
ICPartitions.C_SINGLE_LINE_COMMENT,
ICPartitions.C_STRING,
ICPartitions.C_CHARACTER,
IDocument.DEFAULT_CONTENT_TYPE
};
FastPartitioner partitioner= new FastPartitioner(new FastCPartitionScanner(), types);
partitioner.connect(document);
document.setDocumentPartitioner(ICPartitions.C_PARTITIONING, partitioner);
}
/**
* Installs a C partitioner with <code>document</code>.
*
* @param document the document
*/
private static void removeCPartitioner(Document document) {
document.setDocumentPartitioner(ICPartitions.C_PARTITIONING, null);
}
private void smartPaste(IDocument document, DocumentCommand command) {
int newOffset= command.offset;
int newLength= command.length;
String newText= command.text;
try {
CHeuristicScanner scanner= new CHeuristicScanner(document);
CIndenter indenter= new CIndenter(document, scanner, fProject);
int offset= newOffset;
// reference position to get the indent from
int refOffset= indenter.findReferencePosition(offset);
if (refOffset == CHeuristicScanner.NOT_FOUND)
return;
int peerOffset= getPeerPosition(document, command);
peerOffset= indenter.findReferencePosition(peerOffset);
refOffset= Math.min(refOffset, peerOffset);
// eat any WS before the insertion to the beginning of the line
int firstLine= 1; // don't format the first line per default, as it has other content before it
IRegion line= document.getLineInformationOfOffset(offset);
String notSelected= document.get(line.getOffset(), offset - line.getOffset());
if (notSelected.trim().length() == 0) {
newLength += notSelected.length();
newOffset= line.getOffset();
firstLine= 0;
}
// prefix: the part we need for formatting but won't paste
IRegion refLine= document.getLineInformationOfOffset(refOffset);
String prefix= document.get(refLine.getOffset(), newOffset - refLine.getOffset());
// handle the indentation computation inside a temporary document
Document temp= new Document(prefix + newText);
DocumentRewriteSession session= temp.startRewriteSession(DocumentRewriteSessionType.STRICTLY_SEQUENTIAL);
scanner= new CHeuristicScanner(temp);
indenter= new CIndenter(temp, scanner, fProject);
installCPartitioner(temp);
// indent the first and second line
// compute the relative indentation difference from the second line
// (as the first might be partially selected) and use the value to
// indent all other lines.
boolean isIndentDetected= false;
StringBuffer addition= new StringBuffer();
int insertLength= 0;
int first= document.computeNumberOfLines(prefix) + firstLine; // don't format first line
int lines= temp.getNumberOfLines();
boolean changed= false;
for (int l= first; l < lines; l++) { // we don't change the number of lines while adding indents
IRegion r= temp.getLineInformation(l);
int lineOffset= r.getOffset();
int lineLength= r.getLength();
if (lineLength == 0) // don't modify empty lines
continue;
if (!isIndentDetected) {
// indent the first pasted line
String current= getCurrentIndent(temp, l);
StringBuffer correct= indenter.computeIndentation(lineOffset);
if (correct == null)
return; // bail out
insertLength= subtractIndent(correct, current, addition);
if (l != first && temp.get(lineOffset, lineLength).trim().length() != 0) {
isIndentDetected= true;
if (insertLength == 0) {
// no adjustment needed, bail out
if (firstLine == 0) {
// but we still need to adjust the first line
command.offset= newOffset;
command.length= newLength;
if (changed)
break; // still need to get the leading indent of the first line
}
return;
}
removeCPartitioner(temp);
} else {
changed= insertLength != 0;
}
}
// relatively indent all pasted lines
if (insertLength > 0)
addIndent(temp, l, addition);
else if (insertLength < 0)
cutIndent(temp, l, -insertLength);
}
temp.stopRewriteSession(session);
newText= temp.get(prefix.length(), temp.getLength() - prefix.length());
command.offset= newOffset;
command.length= newLength;
command.text= newText;
} catch (BadLocationException e) {
CUIPlugin.getDefault().log(e);
}
}
/**
* Returns the indentation of the line <code>line</code> in <code>document</code>.
* The returned string may contain pairs of leading slashes that are considered
* part of the indentation. The space before the asterix in a javadoc-like
* comment is not considered part of the indentation.
*
* @param document the document
* @param line the line
* @return the indentation of <code>line</code> in <code>document</code>
* @throws BadLocationException if the document is changed concurrently
*/
private static String getCurrentIndent(Document document, int line) throws BadLocationException {
IRegion region= document.getLineInformation(line);
int from= region.getOffset();
int endOffset= region.getOffset() + region.getLength();
// go behind line comments
int to= from;
while (to < endOffset - 2 && document.get(to, 2).equals(LINE_COMMENT))
to += 2;
while (to < endOffset) {
char ch= document.getChar(to);
if (!Character.isWhitespace(ch))
break;
to++;
}
// don't count the space before javadoc like, asterix-style comment lines
if (to > from && to < endOffset - 1 && document.get(to - 1, 2).equals(" *")) { //$NON-NLS-1$
String type= TextUtilities.getContentType(document, ICPartitions.C_PARTITIONING, to, true);
if (type.equals(ICPartitions.C_MULTI_LINE_COMMENT))
to--;
}
return document.get(from, to - from);
}
/**
* Computes the difference of two indentations and returns the difference in
* length of current and correct. If the return value is positive, <code>addition</code>
* is initialized with a substring of that length of <code>correct</code>.
*
* @param correct the correct indentation
* @param current the current indentation (migth contain non-whitespace)
* @param difference a string buffer - if the return value is positive, it will be cleared and set to the substring of <code>current</code> of that length
* @return the difference in lenght of <code>correct</code> and <code>current</code>
*/
private int subtractIndent(CharSequence correct, CharSequence current, StringBuffer difference) {
int c1= computeVisualLength(correct);
int c2= computeVisualLength(current);
int diff= c1 - c2;
if (diff <= 0)
return diff;
difference.setLength(0);
int len= 0, i= 0;
while (len < diff) {
char c= correct.charAt(i++);
difference.append(c);
len += computeVisualLength(c);
}
return diff;
}
/**
* Indents line <code>line</code> in <code>document</code> with <code>indent</code>.
* Leaves leading comment signs alone.
*
* @param document the document
* @param line the line
* @param indent the indentation to insert
* @throws BadLocationException on concurrent document modification
*/
private static void addIndent(Document document, int line, CharSequence indent) throws BadLocationException {
IRegion region= document.getLineInformation(line);
int insert= region.getOffset();
int endOffset= region.getOffset() + region.getLength();
// go behind line comments
while (insert < endOffset - 2 && document.get(insert, 2).equals(LINE_COMMENT))
insert += 2;
// insert indent
document.replace(insert, 0, indent.toString());
}
/**
* Cuts the visual equivalent of <code>toDelete</code> characters out of the
* indentation of line <code>line</code> in <code>document</code>. Leaves
* leading comment signs alone.
*
* @param document the document
* @param line the line
* @param toDelete the number of space equivalents to delete.
* @throws BadLocationException on concurrent document modification
*/
private void cutIndent(Document document, int line, int toDelete) throws BadLocationException {
IRegion region= document.getLineInformation(line);
int from= region.getOffset();
int endOffset= region.getOffset() + region.getLength();
// go behind line comments
while (from < endOffset - 2 && document.get(from, 2).equals(LINE_COMMENT))
from += 2;
int to= from;
while (toDelete > 0 && to < endOffset) {
char ch= document.getChar(to);
if (!Character.isWhitespace(ch))
break;
toDelete -= computeVisualLength(ch);
if (toDelete >= 0)
to++;
else
break;
}
document.replace(from, to - from, null);
}
/**
* Returns the visual length of a given <code>CharSequence</code> taking into
* account the visual tabulator length.
*
* @param seq the string to measure
* @return the visual length of <code>seq</code>
*/
private int computeVisualLength(CharSequence seq) {
int size= 0;
int tablen= getVisualTabLengthPreference();
for (int i= 0; i < seq.length(); i++) {
char ch= seq.charAt(i);
if (ch == '\t') {
if (tablen != 0)
size += tablen - size % tablen;
// else: size stays the same
} else {
size++;
}
}
return size;
}
/**
* Returns the visual length of a given character taking into
* account the visual tabulator length.
*
* @param ch the character to measure
* @return the visual length of <code>ch</code>
*/
private int computeVisualLength(char ch) {
if (ch == '\t')
return getVisualTabLengthPreference();
else
return 1;
}
/**
* The preference setting for the visual tabulator display.
*
* @return the number of spaces displayed for a tabulator in the editor
*/
private int getVisualTabLengthPreference() {
return CodeFormatterUtil.getTabWidth(fProject);
}
private int getPeerPosition(IDocument document, DocumentCommand command) {
if (document.getLength() == 0)
return 0;
/*
* Search for scope closers in the pasted text and find their opening peers
* in the document.
*/
Document pasted= new Document(command.text);
installCPartitioner(pasted);
int firstPeer= command.offset;
CHeuristicScanner pScanner= new CHeuristicScanner(pasted);
CHeuristicScanner dScanner= new CHeuristicScanner(document);
// add scope relevant after context to peer search
int afterToken= dScanner.nextToken(command.offset + command.length, CHeuristicScanner.UNBOUND);
try {
switch (afterToken) {
case Symbols.TokenRBRACE:
pasted.replace(pasted.getLength(), 0, "}"); //$NON-NLS-1$
break;
case Symbols.TokenRPAREN:
pasted.replace(pasted.getLength(), 0, ")"); //$NON-NLS-1$
break;
case Symbols.TokenRBRACKET:
pasted.replace(pasted.getLength(), 0, "]"); //$NON-NLS-1$
break;
}
} catch (BadLocationException e) {
// cannot happen
Assert.isTrue(false);
}
int pPos= 0; // paste text position (increasing from 0)
int dPos= Math.max(0, command.offset - 1); // document position (decreasing from paste offset)
while (true) {
int token= pScanner.nextToken(pPos, CHeuristicScanner.UNBOUND);
pPos= pScanner.getPosition();
switch (token) {
case Symbols.TokenLBRACE:
case Symbols.TokenLBRACKET:
case Symbols.TokenLPAREN:
pPos= skipScope(pScanner, pPos, token);
if (pPos == CHeuristicScanner.NOT_FOUND)
return firstPeer;
break; // closed scope -> keep searching
case Symbols.TokenRBRACE:
int peer= dScanner.findOpeningPeer(dPos, '{', '}');
dPos= peer - 1;
if (peer == CHeuristicScanner.NOT_FOUND)
return firstPeer;
firstPeer= peer;
break; // keep searching
case Symbols.TokenRBRACKET:
peer= dScanner.findOpeningPeer(dPos, '[', ']');
dPos= peer - 1;
if (peer == CHeuristicScanner.NOT_FOUND)
return firstPeer;
firstPeer= peer;
break; // keep searching
case Symbols.TokenRPAREN:
peer= dScanner.findOpeningPeer(dPos, '(', ')');
dPos= peer - 1;
if (peer == CHeuristicScanner.NOT_FOUND)
return firstPeer;
firstPeer= peer;
break; // keep searching
case Symbols.TokenCASE:
case Symbols.TokenDEFAULT:
{
CIndenter indenter= new CIndenter(document, dScanner, fProject);
peer= indenter.findReferencePosition(dPos, false, false, false, true, false);
if (peer == CHeuristicScanner.NOT_FOUND)
return firstPeer;
firstPeer= peer;
}
break; // keep searching
case Symbols.TokenPUBLIC:
case Symbols.TokenPROTECTED:
case Symbols.TokenPRIVATE:
{
CIndenter indenter= new CIndenter(document, dScanner, fProject);
peer= indenter.findReferencePosition(dPos, false, false, false, false, true);
if (peer == CHeuristicScanner.NOT_FOUND)
return firstPeer;
firstPeer= peer;
}
break; // keep searching
case Symbols.TokenEOF:
return firstPeer;
default:
// keep searching
}
}
}
/**
* Skips the scope opened by <code>token</code> in <code>document</code>,
* returns either the position of the
* @param pos
* @param token
* @return the position after the scope
*/
private static int skipScope(CHeuristicScanner scanner, int pos, int token) {
int openToken= token;
int closeToken;
switch (token) {
case Symbols.TokenLPAREN:
closeToken= Symbols.TokenRPAREN;
break;
case Symbols.TokenLBRACKET:
closeToken= Symbols.TokenRBRACKET;
break;
case Symbols.TokenLBRACE:
closeToken= Symbols.TokenRBRACE;
break;
default:
Assert.isTrue(false);
return -1; // dummy
}
int depth= 1;
int p= pos;
while (true) {
int tok= scanner.nextToken(p, CHeuristicScanner.UNBOUND);
p= scanner.getPosition();
if (tok == openToken) {
depth++;
} else if (tok == closeToken) {
depth--;
if (depth == 0)
return p + 1;
} else if (tok == Symbols.TokenEOF) {
return CHeuristicScanner.NOT_FOUND;
}
}
}
private void smartIndentOnKeypress(IDocument document, DocumentCommand command) {
switch (command.text.charAt(0)) {
case '}':
@ -530,42 +975,44 @@ public class CAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy {
case 'e':
smartIndentUponE(document, command);
break;
case ':':
smartIndentAfterColumn(document, command);
break;
}
}
private void smartIndentUponE(IDocument d, DocumentCommand c) {
if (c.offset < 4 || d.getLength() == 0)
private void smartIndentUponE(IDocument doc, DocumentCommand c) {
if (c.offset < 4 || doc.getLength() == 0)
return;
try {
String content = d.get(c.offset - 3, 3);
String content = doc.get(c.offset - 3, 3);
if (content.equals("els")) { //$NON-NLS-1$
CHeuristicScanner scanner = new CHeuristicScanner(d);
CHeuristicScanner scanner = new CHeuristicScanner(doc);
int p = c.offset - 3;
// current line
int line = d.getLineOfOffset(p);
int lineOffset = d.getLineOffset(line);
int line = doc.getLineOfOffset(p);
int lineOffset = doc.getLineOffset(line);
// make sure we don't have any leading comments etc.
if (d.get(lineOffset, p - lineOffset).trim().length() != 0)
if (doc.get(lineOffset, p - lineOffset).trim().length() != 0)
return;
// line of last javacode
// Line of last C code
int pos = scanner.findNonWhitespaceBackward(p - 1, CHeuristicScanner.UNBOUND);
if (pos == -1)
return;
int lastLine = d.getLineOfOffset(pos);
int lastLine = doc.getLineOfOffset(pos);
// only shift if the last java line is further up and is a braceless block candidate
// Only shift if the last C line is further up and is a braceless block candidate
if (lastLine < line) {
CIndenter indenter = new CIndenter(d, scanner, fProject);
int ref = indenter.findReferencePosition(p, true, false, false, false);
CIndenter indenter = new CIndenter(doc, scanner, fProject);
int ref = indenter.findReferencePosition(p, true, false, false, false, false);
if (ref == CHeuristicScanner.NOT_FOUND)
return;
int refLine = d.getLineOfOffset(ref);
String indent = getIndentOfLine(d, refLine);
int refLine = doc.getLineOfOffset(ref);
String indent = getIndentOfLine(doc, refLine);
if (indent != null) {
c.text = indent.toString() + "else"; //$NON-NLS-1$
@ -578,35 +1025,34 @@ public class CAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy {
}
if (content.equals("cas")) { //$NON-NLS-1$
CHeuristicScanner scanner = new CHeuristicScanner(d);
CHeuristicScanner scanner = new CHeuristicScanner(doc);
int p = c.offset - 3;
// current line
int line = d.getLineOfOffset(p);
int lineOffset = d.getLineOffset(line);
int line = doc.getLineOfOffset(p);
int lineOffset = doc.getLineOffset(line);
// make sure we don't have any leading comments etc.
if (d.get(lineOffset, p - lineOffset).trim().length() != 0)
if (doc.get(lineOffset, p - lineOffset).trim().length() != 0)
return;
// line of last javacode
// Line of last C code
int pos = scanner.findNonWhitespaceBackward(p - 1, CHeuristicScanner.UNBOUND);
if (pos == -1)
return;
int lastLine = d.getLineOfOffset(pos);
int lastLine = doc.getLineOfOffset(pos);
// only shift if the last java line is further up and is a braceless block candidate
// Only shift if the last C line is further up and is a braceless block candidate
if (lastLine < line) {
CIndenter indenter = new CIndenter(d, scanner, fProject);
int ref = indenter.findReferencePosition(p, false, false, false, true);
CIndenter indenter = new CIndenter(doc, scanner, fProject);
int ref = indenter.findReferencePosition(p, false, false, false, true, false);
if (ref == CHeuristicScanner.NOT_FOUND)
return;
int refLine = d.getLineOfOffset(ref);
int refLine = doc.getLineOfOffset(ref);
int nextToken = scanner.nextToken(ref, CHeuristicScanner.UNBOUND);
String indent;
if (nextToken == Symbols.TokenCASE || nextToken == Symbols.TokenDEFAULT)
indent = getIndentOfLine(d, refLine);
indent = getIndentOfLine(doc, refLine);
else // at the brace of the switch
indent = indenter.computeIndentation(p).toString();
@ -624,6 +1070,72 @@ public class CAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy {
}
}
private void smartIndentAfterColumn(IDocument doc, DocumentCommand c) {
try {
int offset = c.offset;
// Current line
int line = doc.getLineOfOffset(offset);
IRegion startLine = doc.getLineInformationOfOffset(offset);
int lineOffset = startLine.getOffset();
CHeuristicScanner scanner = new CHeuristicScanner(doc);
int prevToken = scanner.previousToken(offset - 1, lineOffset);
switch (prevToken) {
case Symbols.TokenDEFAULT:
case Symbols.TokenPUBLIC:
case Symbols.TokenPROTECTED:
case Symbols.TokenPRIVATE:
break;
default:
return;
}
int p = scanner.getPosition() + 1;
// Make sure we don't have any leading comments etc.
if (doc.get(lineOffset, p - lineOffset).trim().length() != 0)
return;
// Line of last C code
int pos = scanner.findNonWhitespaceBackward(p - 1, CHeuristicScanner.UNBOUND);
if (pos == -1)
return;
int lastLine = doc.getLineOfOffset(pos);
// Only shift if the last C line is further up and is a braceless block candidate
if (lastLine < line) {
CIndenter indenter = new CIndenter(doc, scanner, fProject);
int ref;
if (prevToken == Symbols.TokenDEFAULT)
ref = indenter.findReferencePosition(p, false, false, false, true, false);
else
ref = indenter.findReferencePosition(p, false, false, false, false, true);
if (ref == CHeuristicScanner.NOT_FOUND)
return;
int refLine = doc.getLineOfOffset(ref);
int nextToken = scanner.nextToken(ref, CHeuristicScanner.UNBOUND);
String indent;
if (nextToken == Symbols.TokenCASE || nextToken == Symbols.TokenDEFAULT ||
nextToken == Symbols.TokenPUBLIC || nextToken == Symbols.TokenPROTECTED ||
nextToken == Symbols.TokenPRIVATE)
indent = getIndentOfLine(doc, refLine);
else // at the brace of the switch or the class
indent = indenter.computeIndentation(p).toString();
if (indent != null) {
c.text = indent.toString() + doc.get(p, offset - p) + c.text;
c.length += c.offset - lineOffset;
c.offset = lineOffset;
}
}
return;
} catch (BadLocationException e) {
CUIPlugin.getDefault().log(e);
}
}
/*
* @see org.eclipse.jface.text.IAutoEditStrategy#customizeDocumentCommand(IDocument, DocumentCommand)
*/
@ -649,9 +1161,8 @@ public class CAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy {
CCommentAutoIndentStrategy.commentIndentForCommentEnd(d, c);
} else if (c.text.length() == 1) {
smartIndentOnKeypress(d, c);
// TODO Support smart paste.
// } else if (c.text.length() > 1 && getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_PASTE)) {
// smartPaste(d, c); // no smart backspace for paste
} else if (c.text.length() > 1 && getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_PASTE)) {
smartPaste(d, c); // no smart backspace for paste
}
}

View file

@ -82,6 +82,10 @@ public class CCommentScanner extends AbstractCScanner
private String fDefaultTokenProperty;
private String[] fTokenProperties;
public CCommentScanner(IColorManager manager, IPreferenceStore store, String defaultTokenProperty) {
this(manager, store, null, defaultTokenProperty, new String[] { defaultTokenProperty, TASK_TAG });
}
public CCommentScanner(IColorManager manager, IPreferenceStore store, Preferences coreStore, String defaultTokenProperty) {
this(manager, store, coreStore, defaultTokenProperty, new String[] { defaultTokenProperty, TASK_TAG });
}

View file

@ -16,7 +16,7 @@ import java.util.Map;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.formatter.CodeFormatter;
import org.eclipse.cdt.core.formatter.CodeFormatterConstants;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.cdt.core.model.CoreModel;
import org.eclipse.cdt.core.parser.ParserLanguage;
import org.eclipse.cdt.internal.corext.util.CodeFormatterUtil;
@ -142,8 +142,8 @@ public class CFormattingStrategy extends ContextBasedFormattingStrategy {
} else
preferences= new HashMap(CCorePlugin.getOptions());
preferences.put(CodeFormatterConstants.FORMATTER_LANGUAGE, language);
preferences.put(CodeFormatterConstants.FORMATTER_CURRENT_FILE, activeFile);
preferences.put(DefaultCodeFormatterConstants.FORMATTER_LANGUAGE, language);
preferences.put(DefaultCodeFormatterConstants.FORMATTER_CURRENT_FILE, activeFile);
context.storeToMap(CUIPlugin.getDefault().getPreferenceStore(), preferences, false);
context.setProperty(FormattingContextProperties.CONTEXT_PREFERENCES, preferences);

View file

@ -268,7 +268,7 @@ public final class CHeuristicScanner implements Symbols {
}
/**
* Calls <code>this(document, IJavaPartitions.JAVA_PARTITIONING, IDocument.DEFAULT_CONTENT_TYPE)</code>.
* Calls <code>this(document, ICPartitions.JAVA_PARTITIONING, IDocument.DEFAULT_CONTENT_TYPE)</code>.
*
* @param document the document to scan.
*/
@ -473,17 +473,28 @@ public final class CHeuristicScanner implements Symbols {
return TokenWHILE;
break;
case 6:
if ("delete".equals(s)) //$NON-NLS-1$
return TokenDELETE;
if ("public".equals(s)) //$NON-NLS-1$
return TokenPUBLIC;
if ("return".equals(s)) //$NON-NLS-1$
return TokenRETURN;
if ("static".equals(s)) //$NON-NLS-1$
return TokenSTATIC;
if ("struct".equals(s)) //$NON-NLS-1$
return TokenSTRUCT;
if ("switch".equals(s)) //$NON-NLS-1$
return TokenSWITCH;
break;
case 7:
if ("default".equals(s)) //$NON-NLS-1$
return TokenDEFAULT;
if ("private".equals(s)) //$NON-NLS-1$
return TokenPRIVATE;
break;
case 9:
if ("protected".equals(s)) //$NON-NLS-1$
return TokenPROTECTED;
}
return TokenIDENT;
}

View file

@ -7,11 +7,12 @@
*
* Contributors:
* IBM Corporation - initial API and implementation
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.ui.text;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.formatter.CodeFormatterConstants;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.internal.corext.util.CodeFormatterUtil;
@ -45,8 +46,8 @@ public final class CIndenter {
final boolean prefTernaryDeepAlign;
final int prefTernaryIndent;
final int prefCaseIndent;
final int prefAssignmentIndent;
final int prefCaseBlockIndent;
final int prefAssignmentIndent;
final int prefSimpleIndent;
final int prefBracketIndent;
final boolean prefMethodDeclDeepIndent;
@ -58,6 +59,7 @@ public final class CIndenter {
final int prefBlockIndent;
final int prefMethodBodyIndent;
final int prefTypeIndent;
final int prefAccessSpecifierIndent;
final boolean prefIndentBracesForBlocks;
final boolean prefIndentBracesForArrays;
final boolean prefIndentBracesForMethods;
@ -93,8 +95,8 @@ public final class CIndenter {
prefTernaryDeepAlign= prefTernaryDeepAlign();
prefTernaryIndent= prefTernaryIndent();
prefCaseIndent= prefCaseIndent();
prefAssignmentIndent= prefAssignmentIndent();
prefCaseBlockIndent= prefCaseBlockIndent();
prefAssignmentIndent= prefAssignmentIndent();
prefIndentBracesForBlocks= prefIndentBracesForBlocks();
prefSimpleIndent= prefSimpleIndent();
prefBracketIndent= prefBracketIndent();
@ -106,15 +108,16 @@ public final class CIndenter {
prefParenthesisIndent= prefParenthesisIndent();
prefMethodBodyIndent= prefMethodBodyIndent();
prefTypeIndent= prefTypeIndent();
prefAccessSpecifierIndent= prefAccessSpecifierIndent();
prefIndentBracesForArrays= prefIndentBracesForArrays();
prefIndentBracesForMethods= prefIndentBracesForMethods();
prefIndentBracesForTypes= prefIndentBracesForTypes();
prefHasGenerics= hasGenerics();
prefTabChar= getCoreFormatterOption(CodeFormatterConstants.FORMATTER_TAB_CHAR);
prefTabChar= getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR);
}
private boolean prefUseTabs() {
return !CCorePlugin.SPACE.equals(getCoreFormatterOption(CodeFormatterConstants.FORMATTER_TAB_CHAR));
return !CCorePlugin.SPACE.equals(getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR));
}
private int prefTabSize() {
@ -130,9 +133,9 @@ public final class CIndenter {
}
private int prefArrayIndent() {
String option= getCoreFormatterOption(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_ARRAY_INITIALIZER);
String option= getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_ARRAY_INITIALIZER);
try {
if (CodeFormatterConstants.getIndentStyle(option) == CodeFormatterConstants.INDENT_BY_ONE)
if (DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_BY_ONE)
return 1;
} catch (IllegalArgumentException e) {
// ignore and return default
@ -142,9 +145,9 @@ public final class CIndenter {
}
private boolean prefArrayDeepIndent() {
String option= getCoreFormatterOption(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_ARRAY_INITIALIZER);
String option= getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_ARRAY_INITIALIZER);
try {
return CodeFormatterConstants.getIndentStyle(option) == CodeFormatterConstants.INDENT_ON_COLUMN;
return DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_ON_COLUMN;
} catch (IllegalArgumentException e) {
// ignore and return default
}
@ -153,9 +156,9 @@ public final class CIndenter {
}
private boolean prefTernaryDeepAlign() {
String option= getCoreFormatterOption(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_CONDITIONAL_EXPRESSION);
String option= getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_CONDITIONAL_EXPRESSION);
try {
return CodeFormatterConstants.getIndentStyle(option) == CodeFormatterConstants.INDENT_ON_COLUMN;
return DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_ON_COLUMN;
} catch (IllegalArgumentException e) {
// ignore and return default
}
@ -163,9 +166,9 @@ public final class CIndenter {
}
private int prefTernaryIndent() {
String option= getCoreFormatterOption(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_CONDITIONAL_EXPRESSION);
String option= getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_CONDITIONAL_EXPRESSION);
try {
if (CodeFormatterConstants.getIndentStyle(option) == CodeFormatterConstants.INDENT_BY_ONE)
if (DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_BY_ONE)
return 1;
else
return prefContinuationIndent();
@ -177,7 +180,17 @@ public final class CIndenter {
}
private int prefCaseIndent() {
if (CodeFormatterConstants.TRUE.equals(getCoreFormatterOption(CodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_SWITCH)))
if (DefaultCodeFormatterConstants.TRUE.equals(getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_SWITCH)))
return prefBlockIndent();
else
return 0;
}
private int prefCaseBlockIndent() {
if (true)
return prefBlockIndent();
if (DefaultCodeFormatterConstants.TRUE.equals(getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_CASES)))
return prefBlockIndent();
else
return 0;
@ -187,16 +200,6 @@ public final class CIndenter {
return prefBlockIndent();
}
private int prefCaseBlockIndent() {
if (true)
return prefBlockIndent();
if (CodeFormatterConstants.TRUE.equals(getCoreFormatterOption(CodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_CASES)))
return prefBlockIndent();
else
return 0;
}
private int prefSimpleIndent() {
if (prefIndentBracesForBlocks() && prefBlockIndent() == 0)
return 1;
@ -208,9 +211,9 @@ public final class CIndenter {
}
private boolean prefMethodDeclDeepIndent() {
String option= getCoreFormatterOption(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION);
String option= getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION);
try {
return CodeFormatterConstants.getIndentStyle(option) == CodeFormatterConstants.INDENT_ON_COLUMN;
return DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_ON_COLUMN;
} catch (IllegalArgumentException e) {
// ignore and return default
}
@ -219,9 +222,9 @@ public final class CIndenter {
}
private int prefMethodDeclIndent() {
String option= getCoreFormatterOption(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION);
String option= getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION);
try {
if (CodeFormatterConstants.getIndentStyle(option) == CodeFormatterConstants.INDENT_BY_ONE)
if (DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_BY_ONE)
return 1;
else
return prefContinuationIndent();
@ -232,9 +235,9 @@ public final class CIndenter {
}
private boolean prefMethodCallDeepIndent() {
String option= getCoreFormatterOption(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION);
String option= getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION);
try {
return CodeFormatterConstants.getIndentStyle(option) == CodeFormatterConstants.INDENT_ON_COLUMN;
return DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_ON_COLUMN;
} catch (IllegalArgumentException e) {
// ignore and return default
}
@ -242,9 +245,9 @@ public final class CIndenter {
}
private int prefMethodCallIndent() {
String option= getCoreFormatterOption(CodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION);
String option= getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION);
try {
if (CodeFormatterConstants.getIndentStyle(option) == CodeFormatterConstants.INDENT_BY_ONE)
if (DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_BY_ONE)
return 1;
else
return prefContinuationIndent();
@ -259,9 +262,9 @@ public final class CIndenter {
if (true) // don't do parenthesis deep indentation
return false;
String option= getCoreFormatterOption(CodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION);
String option= getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION);
try {
return CodeFormatterConstants.getIndentStyle(option) == CodeFormatterConstants.INDENT_ON_COLUMN;
return DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_ON_COLUMN;
} catch (IllegalArgumentException e) {
// ignore and return default
}
@ -274,53 +277,61 @@ public final class CIndenter {
}
private int prefBlockIndent() {
String option= getCoreFormatterOption(CodeFormatterConstants.FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BLOCK);
if (CodeFormatterConstants.FALSE.equals(option))
String option= getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BLOCK);
if (DefaultCodeFormatterConstants.FALSE.equals(option))
return 0;
return 1; // sensible default
}
private int prefMethodBodyIndent() {
if (CodeFormatterConstants.FALSE.equals(getCoreFormatterOption(CodeFormatterConstants.FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BODY)))
if (DefaultCodeFormatterConstants.FALSE.equals(getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BODY)))
return 0;
return 1; // sensible default
}
private int prefTypeIndent() {
String option= getCoreFormatterOption(CodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_TYPE_HEADER);
if (CodeFormatterConstants.FALSE.equals(option))
String option= getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ACCESS_SPECIFIER);
if (DefaultCodeFormatterConstants.FALSE.equals(option))
return 0;
return 1; // sensible default
}
private int prefAccessSpecifierIndent() {
if (DefaultCodeFormatterConstants.TRUE.equals(getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_INDENT_ACCESS_SPECIFIER_COMPARE_TO_TYPE_HEADER)))
return prefBlockIndent();
else
return 0;
}
private boolean prefIndentBracesForBlocks() {
return CodeFormatterConstants.NEXT_LINE_SHIFTED.equals(getCoreFormatterOption(CodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_BLOCK));
return DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED.equals(getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_BLOCK));
}
private boolean prefIndentBracesForArrays() {
return CodeFormatterConstants.NEXT_LINE_SHIFTED.equals(getCoreFormatterOption(CodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ARRAY_INITIALIZER));
return DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED.equals(getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ARRAY_INITIALIZER));
}
private boolean prefIndentBracesForMethods() {
return CodeFormatterConstants.NEXT_LINE_SHIFTED.equals(getCoreFormatterOption(CodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION));
return DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED.equals(getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION));
}
private boolean prefIndentBracesForTypes() {
return CodeFormatterConstants.NEXT_LINE_SHIFTED.equals(getCoreFormatterOption(CodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION));
return DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED.equals(getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION));
}
private int prefContinuationIndent() {
try {
return Integer.parseInt(getCoreFormatterOption(CodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION));
return Integer.parseInt(getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION));
} catch (NumberFormatException e) {
// ignore and return default
}
return 2; // sensible default
}
private boolean hasGenerics() {
return true;
}
@ -404,7 +415,6 @@ public final class CIndenter {
* if it cannot be determined
*/
private StringBuffer getReferenceIndentation(int offset, boolean assumeOpeningBrace) {
int unit;
if (assumeOpeningBrace)
unit= findReferencePosition(offset, Symbols.TokenLBRACE);
@ -416,7 +426,6 @@ public final class CIndenter {
return null;
return getLeadingWhitespace(unit);
}
/**
@ -441,7 +450,6 @@ public final class CIndenter {
* determined
*/
public StringBuffer computeIndentation(int offset, boolean assumeOpeningBrace) {
StringBuffer reference= getReferenceIndentation(offset, assumeOpeningBrace);
// handle special alignment
@ -459,10 +467,29 @@ public final class CIndenter {
if (reference == null)
return null;
// add additional indent
// Add additional indent
return createReusingIndent(reference, fIndent);
}
/**
* Computes the indentation for a continuation line at <code>offset</code>.
*
* @param offset the offset in the document
* @return a StringBuffer which reflects the correct indentation for
* the line in which offset resides, or <code>null</code> if it cannot be
* determined.
* @throws BadLocationException
*/
public StringBuffer computeContinuationLineIndentation(int offset) throws BadLocationException {
StringBuffer reference= getLeadingWhitespace(offset);
IRegion line= fDocument.getLineInformationOfOffset(offset);
String string= fDocument.get(line.getOffset(), offset - line.getOffset());
if (string.trim().length() == 0)
return reference;
// Add additional indent
return createReusingIndent(reference, fPrefs.prefContinuationIndent);
}
/**
* Computes the length of a <code>CharacterSequence</code>, counting
* a tab character as the size until the next tab stop and every other
@ -572,7 +599,6 @@ public final class CIndenter {
try {
int spaces= 0;
while (start < indent) {
char ch= fDocument.getChar(start);
if (ch == '\t') {
ret.append('\t');
@ -609,12 +635,11 @@ public final class CIndenter {
* @return the modified <code>buffer</code> reflecting the indentation
* adapted to <code>additional</code>
*/
private StringBuffer createReusingIndent(StringBuffer buffer, int additional) {
public StringBuffer createReusingIndent(StringBuffer buffer, int additional) {
int refLength= computeVisualLength(buffer);
int addLength= fPrefs.prefIndentationSize * additional; // may be < 0
int totalLength= Math.max(0, refLength + addLength);
// copy the reference indentation for the indent up to the last tab
// stop within the maxCopy area
int minLength= Math.min(totalLength, refLength);
@ -622,7 +647,6 @@ public final class CIndenter {
int maxCopyLength= tabSize > 0 ? minLength - minLength % tabSize : minLength; // maximum indent to copy
stripExceedingChars(buffer, maxCopyLength);
// add additional indent
int missing= totalLength - maxCopyLength;
final int tabs, spaces;
@ -632,7 +656,7 @@ public final class CIndenter {
} else if (CCorePlugin.TAB.equals(fPrefs.prefTabChar)) {
tabs= tabSize > 0 ? missing / tabSize : 0;
spaces= tabSize > 0 ? missing % tabSize : missing;
} else if (CodeFormatterConstants.MIXED.equals(fPrefs.prefTabChar)) {
} else if (DefaultCodeFormatterConstants.MIXED.equals(fPrefs.prefTabChar)) {
tabs= tabSize > 0 ? missing / tabSize : 0;
spaces= tabSize > 0 ? missing % tabSize : missing;
} else {
@ -713,6 +737,7 @@ public final class CIndenter {
boolean matchBrace= false;
boolean matchParen= false;
boolean matchCase= false;
boolean matchAccessSpecifier= false;
// account for un-indentation characters already typed in, but after position
// if they are on a line by themselves, the indentation gets adjusted
@ -732,11 +757,20 @@ public final class CIndenter {
case Symbols.TokenELSE:
danglingElse= true;
break;
case Symbols.TokenCASE:
case Symbols.TokenDEFAULT:
if (isFirstTokenOnLine)
matchCase= true;
break;
case Symbols.TokenPUBLIC:
case Symbols.TokenPROTECTED:
case Symbols.TokenPRIVATE:
if (isFirstTokenOnLine)
matchAccessSpecifier= true;
break;
case Symbols.TokenLBRACE: // for opening-brace-on-new-line style
if (bracelessBlockStart && !fPrefs.prefIndentBracesForBlocks)
unindent= true;
@ -745,10 +779,12 @@ public final class CIndenter {
else if (!bracelessBlockStart && fPrefs.prefIndentBracesForMethods)
indent= true;
break;
case Symbols.TokenRBRACE: // closing braces get unindented
if (isFirstTokenOnLine)
matchBrace= true;
break;
case Symbols.TokenRPAREN:
if (isFirstTokenOnLine)
matchParen= true;
@ -761,7 +797,7 @@ public final class CIndenter {
danglingElse= false;
}
int ref= findReferencePosition(offset, danglingElse, matchBrace, matchParen, matchCase);
int ref= findReferencePosition(offset, danglingElse, matchBrace, matchParen, matchCase, matchAccessSpecifier);
if (unindent)
fIndent--;
if (indent)
@ -787,10 +823,14 @@ public final class CIndenter {
* @param matchCase whether the position of a switch statement reference
* should be returned (either an earlier case statement or the
* switch block brace)
* @param matchAccessSpecifier whether the position of a class body reference
* should be returned (either an earlier public/protected/private
* or the class body brace)
* @return the reference statement relative to which <code>position</code>
* should be indented, or {@link CHeuristicScanner#NOT_FOUND}
*/
public int findReferencePosition(int offset, boolean danglingElse, boolean matchBrace, boolean matchParen, boolean matchCase) {
public int findReferencePosition(int offset, boolean danglingElse, boolean matchBrace, boolean matchParen,
boolean matchCase, boolean matchAccessSpecifier) {
fIndent= 0; // the indentation modification
fAlign= CHeuristicScanner.NOT_FOUND;
fPosition= offset;
@ -816,7 +856,7 @@ public final class CIndenter {
} else {
// if we can't find the matching brace, the heuristic is to unindent
// by one against the normal position
int pos= findReferencePosition(offset, danglingElse, false, matchParen, matchCase);
int pos= findReferencePosition(offset, danglingElse, false, matchParen, matchCase, matchAccessSpecifier);
fIndent--;
return pos;
}
@ -829,7 +869,7 @@ public final class CIndenter {
else {
// if we can't find the matching paren, the heuristic is to unindent
// by one against the normal position
int pos= findReferencePosition(offset, danglingElse, matchBrace, false, matchCase);
int pos= findReferencePosition(offset, danglingElse, matchBrace, false, matchCase, matchAccessSpecifier);
fIndent--;
return pos;
}
@ -841,6 +881,12 @@ public final class CIndenter {
return matchCaseAlignment();
}
// the only reliable way to get case labels aligned (due to many different styles of using braces in a block)
// is to go for another case statement, or the scope opening brace
if (matchAccessSpecifier) {
return matchAccessSpecifierAlignment();
}
nextToken();
switch (fToken) {
case Symbols.TokenGREATERTHAN:
@ -930,7 +976,6 @@ public final class CIndenter {
// if we are inside a continued expression, then either align with a previous line that has indentation
// or indent from the expression start line (either a scope introducer or the start of the expr).
return skipToPreviousListItemOrListStart();
}
}
@ -1060,9 +1105,7 @@ public final class CIndenter {
default:
// keep searching
}
}
}
@ -1085,12 +1128,16 @@ public final class CIndenter {
while (true) {
nextToken();
switch (fToken) {
// search for case labels, which consist of (possibly qualified) identifiers or numbers
case Symbols.TokenIDENT:
case Symbols.TokenOTHER: // dots for qualified constants
continue;
case Symbols.TokenCASE:
case Symbols.TokenDEFAULT:
case Symbols.TokenPUBLIC:
case Symbols.TokenPROTECTED:
case Symbols.TokenPRIVATE:
return false;
default:
@ -1117,10 +1164,12 @@ public final class CIndenter {
case Symbols.TokenLBRACKET:
case Symbols.TokenEOF:
return fPosition;
case Symbols.TokenLBRACE:
// opening brace of switch statement
fIndent= fPrefs.prefCaseIndent;
return fPosition;
case Symbols.TokenCASE:
case Symbols.TokenDEFAULT:
// align with previous label
@ -1138,7 +1187,52 @@ public final class CIndenter {
default:
// keep searching
continue;
}
}
}
/**
* Returns as a reference any previous <code>switch</code> labels (<code>case</code>
* or <code>default</code>) or the offset of the brace that scopes the class body.
* Sets <code>fIndent</code> to <code>prefAccessSpecifierIndent</code> upon
* a match.
*
* @return the reference offset for an access specifier (public/protected/private)
*/
private int matchAccessSpecifierAlignment() {
while (true) {
nextToken();
switch (fToken) {
// invalid cases: another case label or an LBRACE must come before a case
// -> bail out with the current position
case Symbols.TokenLPAREN:
case Symbols.TokenLBRACKET:
case Symbols.TokenEOF:
return fPosition;
case Symbols.TokenLBRACE:
// opening brace of switch statement
fIndent= fPrefs.prefAccessSpecifierIndent;
return fPosition;
case Symbols.TokenPUBLIC:
case Symbols.TokenPROTECTED:
case Symbols.TokenPRIVATE:
// align with previous label
fIndent= 0;
return fPosition;
// scopes: skip them
case Symbols.TokenRPAREN:
case Symbols.TokenRBRACKET:
case Symbols.TokenRBRACE:
case Symbols.TokenGREATERTHAN:
skipScope();
break;
default:
// keep searching
continue;
}
}
}

View file

@ -7,16 +7,18 @@
*
* Contributors:
* QNX Software Systems - initial API and implementation
* Sergey Prigogin, Google
*******************************************************************************/
/*
* COutlineInformationControl.java 2004-12-14 / 08:17:41
* $Revision: 1.5 $ $Date: 2005/06/23 16:01:24 $
* $Revision: 1.6 $ $Date: 2006/09/12 06:50:49 $
*
* @author P.Tomaszewski
*/
package org.eclipse.cdt.internal.ui.text;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.MenuManager;
@ -25,9 +27,12 @@ import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlExtension;
import org.eclipse.jface.text.IInformationControlExtension2;
import org.eclipse.jface.text.IInformationControlExtension3;
import org.eclipse.jface.viewers.AbstractTreeViewer;
import org.eclipse.jface.viewers.IContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
@ -75,16 +80,17 @@ import org.eclipse.swt.widgets.Tracker;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.ui.CElementGrouping;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.ui.IWorkingCopyManager;
import org.eclipse.cdt.internal.core.model.CElement;
import org.eclipse.cdt.internal.ui.CPluginImages;
import org.eclipse.cdt.internal.ui.actions.ActionMessages;
import org.eclipse.cdt.internal.ui.actions.OpenActionUtil;
import org.eclipse.cdt.internal.ui.editor.CContentOutlinerProvider;
import org.eclipse.cdt.internal.ui.editor.CEditor;
import org.eclipse.cdt.internal.ui.util.ProblemTreeViewer;
import org.eclipse.cdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
import org.eclipse.cdt.internal.ui.viewsupport.CElementLabels;
@ -100,7 +106,8 @@ import org.eclipse.cdt.internal.ui.viewsupport.StandardCElementLabelProvider;
* @author P.Tomaszewski
*/
public class COutlineInformationControl implements IInformationControl,
IInformationControlExtension, IInformationControlExtension3 {
IInformationControlExtension, IInformationControlExtension2,
IInformationControlExtension3 {
/** If this option is set, location is not restored. */
private static final String STORE_RESTORE_SIZE= "ENABLE_RESTORE_SIZE"; //$NON-NLS-1$
@ -118,8 +125,8 @@ public class COutlineInformationControl implements IInformationControl,
private static final int TEXT_FLAGS = AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | CElementLabels.F_APP_TYPE_SIGNATURE | CElementLabels.M_APP_RETURNTYPE;
private static final int IMAGE_FLAGS = AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS;
/** Source viewer which shows this control. */
CEditor fEditor;
private ICElement fInput = null;
/** Shell for this control. */
Shell fShell;
/** Control's composite. */
@ -162,8 +169,6 @@ public class COutlineInformationControl implements IInformationControl,
/**
* Creates new outline control.
*
* @param editor
* CEditor editor which uses this control.
* @param parent
* Shell parent.
* @param shellStyle
@ -171,10 +176,8 @@ public class COutlineInformationControl implements IInformationControl,
* @param treeStyle
* Style of the tree viewer.
*/
public COutlineInformationControl(CEditor editor, Shell parent,
int shellStyle, int treeStyle) {
public COutlineInformationControl(Shell parent, int shellStyle, int treeStyle) {
super();
this.fEditor = editor;
createShell(parent, shellStyle);
createComposite();
createToolbar();
@ -182,6 +185,52 @@ public class COutlineInformationControl implements IInformationControl,
createTreeeViewer(treeStyle);
}
/**
* {@inheritDoc}
*/
public void setInput(Object information) {
if (information == null || information instanceof String) {
inputChanged(null, null);
return;
}
ICElement ce = (ICElement)information;
ITranslationUnit tu = (ITranslationUnit)ce.getAncestor(ICElement.C_UNIT);
if (tu != null)
fInput = tu;
inputChanged(fInput, information);
}
protected void inputChanged(Object newInput, Object newSelection) {
fFilterText.setText(""); //$NON-NLS-1$
fTreeViewer.setInput(newInput);
if (newSelection != null) {
fTreeViewer.setSelection(new StructuredSelection(newSelection));
}
}
/**
* @return the selected element
*/
protected Object getSelectedElement() {
if (fTreeViewer == null)
return null;
return ((IStructuredSelection) fTreeViewer.getSelection()).getFirstElement();
}
private void gotoSelectedElement() {
Object selectedElement= getSelectedElement();
if (selectedElement != null) {
try {
dispose();
OpenActionUtil.open(selectedElement, true);
} catch (CoreException e) {
CUIPlugin.getDefault().log(e);
}
}
}
/**
* @see org.eclipse.jface.text.IInformationControl#setInformation(java.lang.String)
*/
@ -422,8 +471,6 @@ public class COutlineInformationControl implements IInformationControl,
* @param treeStyle Tree style.
*/
private void createTreeeViewer(int treeStyle) {
final IWorkingCopyManager manager = CUIPlugin.getDefault()
.getWorkingCopyManager();
fTreeViewer = new ProblemTreeViewer(fComposite, treeStyle);
final Tree tree = fTreeViewer.getTree();
tree.setLayoutData(new GridData(GridData.FILL_BOTH));
@ -436,11 +483,10 @@ public class COutlineInformationControl implements IInformationControl,
fTreeViewer.setLabelProvider(new DecoratingCLabelProvider(
new StandardCElementLabelProvider(TEXT_FLAGS, IMAGE_FLAGS), true));
fTreeViewer.setAutoExpandLevel(AbstractTreeViewer.ALL_LEVELS);
fTreeViewer.setInput(manager.getWorkingCopy(fEditor.getEditorInput()));
tree.addKeyListener(createKeyListenerForTreeViewer());
tree.addSelectionListener(createSelectionListenerForTreeViewer());
tree.addMouseMoveListener(createMouseMoveListenerForTreeViewer());
tree.addMouseListener(createMouseListenerForTreeViewer());
tree.addMouseListener(createMouseListenerForTreeViewer(tree));
}
/**
@ -529,30 +575,21 @@ public class COutlineInformationControl implements IInformationControl,
*
* @return Created mouse listener.
*/
private MouseListener createMouseListenerForTreeViewer() {
private MouseListener createMouseListenerForTreeViewer(final Tree tree) {
final MouseListener mouseListener = new MouseAdapter() {
public void mouseUp(MouseEvent e) {
final Tree tree = fTreeViewer.getTree();
if (tree.getSelectionCount() < 1) {
if (tree.getSelectionCount() < 1)
return;
}
if (e.button != 1) {
if (e.button != 1)
return;
}
if (tree.equals(e.getSource())) {
Object o= tree.getItem(new Point(e.x, e.y));
final TreeItem selection = tree.getSelection()[0];
if (selection.equals(o)) {
CElement selectedElement = (CElement) selection
.getData();
fEditor.setSelection(selectedElement);
dispose();
}
if (fComposite != null && !fComposite.isDisposed())
{
fBounds = fComposite.getBounds();
}
TreeItem selection= tree.getSelection()[0];
if (selection.equals(o))
gotoSelectedElement();
}
}
};
@ -620,14 +657,7 @@ public class COutlineInformationControl implements IInformationControl,
* @see org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent)
*/
public void widgetDefaultSelected(SelectionEvent e) {
final TreeItem[] selection = ((Tree) fTreeViewer.getControl())
.getSelection();
if (selection.length > 0) {
CElement selectedElement = (CElement) selection[0]
.getData();
fEditor.setSelection(selectedElement);
dispose();
}
gotoSelectedElement();
}
};
return selectionListener;
@ -1024,5 +1054,4 @@ public class COutlineInformationControl implements IInformationControl,
fIsDeactivationActive = true;
}
}
}

View file

@ -16,7 +16,6 @@ import org.eclipse.cdt.core.model.CModelException;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.core.model.IWorkingCopy;
import org.eclipse.cdt.internal.core.model.CModelManager;
import org.eclipse.cdt.internal.ui.editor.CEditor;
import org.eclipse.cdt.internal.ui.editor.IReconcilingParticipant;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.ui.IWorkingCopyManager;
@ -38,7 +37,7 @@ public class CReconcilingStrategy implements IReconcilingStrategy, IReconcilingS
// used by tests
protected boolean fInitialProcessDone;
public CReconcilingStrategy(CEditor editor) {
public CReconcilingStrategy(ITextEditor editor) {
fEditor= editor;
fManager= CUIPlugin.getDefault().getWorkingCopyManager();
}
@ -49,7 +48,6 @@ public class CReconcilingStrategy implements IReconcilingStrategy, IReconcilingS
public void setDocument(IDocument document) {
}
/*
* @see IReconcilingStrategyExtension#setProgressMonitor(IProgressMonitor)
*/

View file

@ -9,11 +9,16 @@
* IBM Corporation - initial API and implementation
* QNX Software System
* Anton Leherbauer (Wind River Systems)
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.ui.text;
import java.util.Vector;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.content.IContentType;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.DefaultInformationControl;
@ -41,29 +46,37 @@ import org.eclipse.jface.text.rules.RuleBasedScanner;
import org.eclipse.jface.text.source.IAnnotationHover;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IPathEditorInput;
import org.eclipse.ui.editors.text.ILocationProvider;
import org.eclipse.ui.editors.text.TextSourceViewerConfiguration;
import org.eclipse.ui.ide.ResourceUtil;
import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.dom.ast.gnu.c.GCCLanguage;
import org.eclipse.cdt.core.dom.ast.gnu.cpp.GPPLanguage;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.model.ILanguage;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.core.model.LanguageManager;
import org.eclipse.cdt.ui.CElementContentProvider;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.ui.ILanguageUI;
import org.eclipse.cdt.ui.text.ICPartitions;
import org.eclipse.cdt.internal.corext.util.CodeFormatterUtil;
import org.eclipse.cdt.internal.ui.editor.CDocumentProvider;
import org.eclipse.cdt.internal.ui.editor.CEditor;
import org.eclipse.cdt.internal.ui.editor.CElementHyperlinkDetector;
import org.eclipse.cdt.internal.ui.editor.CSourceViewer;
import org.eclipse.cdt.internal.ui.text.c.hover.CEditorTextHoverDescriptor;
import org.eclipse.cdt.internal.ui.text.c.hover.CEditorTextHoverProxy;
import org.eclipse.cdt.internal.ui.text.contentassist.CCompletionProcessor2;
@ -71,12 +84,71 @@ import org.eclipse.cdt.internal.ui.text.contentassist.ContentAssistPreference;
/**
* Configuration for an <code>SourceViewer</code> which shows C code.
* Configuration for an <code>SourceViewer</code> which shows C/C++ code.
*/
public class CSourceViewerConfiguration extends TextSourceViewerConfiguration {
private CTextTools fTextTools;
private CEditor fEditor;
private ITextEditor fTextEditor;
/**
* The document partitioning.
*/
private String fDocumentPartitioning;
/**
* The C++ source code scanner.
*/
private AbstractCScanner fCppCodeScanner;
/**
* The C source code scanner.
*/
private AbstractCScanner fCCodeScanner;
/**
* The C multi-line comment scanner.
*/
private AbstractCScanner fMultilineCommentScanner;
/**
* The C single-line comment scanner.
*/
private AbstractCScanner fSinglelineCommentScanner;
/**
* The C string scanner.
*/
private AbstractCScanner fStringScanner;
/**
* The color manager.
*/
private IColorManager fColorManager;
/**
* The C preprocessor scanner.
*/
private AbstractCScanner fCPreprocessorScanner;
/**
* The C++ preprocessor scanner.
*/
private AbstractCScanner fCppPreprocessorScanner;
/**
* Creates a new C source viewer configuration for viewers in the given editor
* using the given preference store, the color manager and the specified document partitioning.
* <p>
* Creates a C source viewer configuration in the new setup without text tools. Clients are
* allowed to call {@link CSourceViewerConfiguration#handlePropertyChangeEvent(PropertyChangeEvent)}
* and disallowed to call {@link CSourceViewerConfiguration#getPreferenceStore()} on the resulting
* C source viewer configuration.
* </p>
*
* @param colorManager the color manager
* @param preferenceStore the preference store, can be read-only
* @param editor the editor in which the configured viewer(s) will reside, or <code>null</code> if none
* @param partitioning the document partitioning for this configuration, or <code>null</code> for the default partitioning
*/
public CSourceViewerConfiguration(IColorManager colorManager, IPreferenceStore preferenceStore, ITextEditor editor, String partitioning) {
super(preferenceStore);
fColorManager= colorManager;
fTextEditor= editor;
fDocumentPartitioning= partitioning;
initializeScanners();
}
/**
* Creates a new C source viewer configuration for viewers in the given editor using
@ -85,28 +157,37 @@ public class CSourceViewerConfiguration extends TextSourceViewerConfiguration {
* @param tools the C text tools collection to be used
* @param editor the editor in which the configured viewer will reside
*/
public CSourceViewerConfiguration(CTextTools tools, CEditor editor) {
public CSourceViewerConfiguration(CTextTools tools, ITextEditor editor) {
super(CUIPlugin.getDefault().getCombinedPreferenceStore());
fTextTools= tools;
fEditor= editor;
fColorManager= tools.getColorManager();
fTextEditor= editor;
fDocumentPartitioning= fTextTools.getDocumentPartitioning();
fCppCodeScanner= (AbstractCScanner) fTextTools.getCppCodeScanner();
fCCodeScanner= (AbstractCScanner) fTextTools.getCCodeScanner();
fMultilineCommentScanner= (AbstractCScanner) fTextTools.getMultilineCommentScanner();
fSinglelineCommentScanner= (AbstractCScanner) fTextTools.getSinglelineCommentScanner();
fStringScanner= (AbstractCScanner) fTextTools.getStringScanner();
fCPreprocessorScanner= (AbstractCScanner) fTextTools.getCPreprocessorScanner();
fCppPreprocessorScanner= (AbstractCScanner) fTextTools.getCppPreprocessorScanner();
}
/**
* Returns the C multiline comment scanner for this configuration.
* Returns the C multi-line comment scanner for this configuration.
*
* @return the C multiline comment scanner
* @return the C multi-line comment scanner
*/
protected RuleBasedScanner getMultilineCommentScanner() {
return fTextTools.getMultilineCommentScanner();
return fMultilineCommentScanner;
}
/**
* Returns the C singleline comment scanner for this configuration.
* Returns the C single-line comment scanner for this configuration.
*
* @return the C singleline comment scanner
* @return the C single-line comment scanner
*/
protected RuleBasedScanner getSinglelineCommentScanner() {
return fTextTools.getSinglelineCommentScanner();
return fSinglelineCommentScanner;
}
/**
@ -115,7 +196,7 @@ public class CSourceViewerConfiguration extends TextSourceViewerConfiguration {
* @return the C string scanner
*/
protected RuleBasedScanner getStringScanner() {
return fTextTools.getStringScanner();
return fStringScanner;
}
/**
@ -124,7 +205,7 @@ public class CSourceViewerConfiguration extends TextSourceViewerConfiguration {
* @return the C preprocessor scanner
*/
protected RuleBasedScanner getCPreprocessorScanner() {
return fTextTools.getCPreprocessorScanner();
return fCPreprocessorScanner;
}
/**
@ -133,7 +214,7 @@ public class CSourceViewerConfiguration extends TextSourceViewerConfiguration {
* @return the C++ preprocessor scanner
*/
protected RuleBasedScanner getCppPreprocessorScanner() {
return fTextTools.getCppPreprocessorScanner();
return fCppPreprocessorScanner;
}
/**
@ -142,7 +223,7 @@ public class CSourceViewerConfiguration extends TextSourceViewerConfiguration {
* @return the color manager
*/
protected IColorManager getColorManager() {
return fTextTools.getColorManager();
return fColorManager;
}
/**
@ -150,21 +231,18 @@ public class CSourceViewerConfiguration extends TextSourceViewerConfiguration {
*
* @return the enclosing editor
*/
protected ITextEditor getEditor() {
return fEditor;
public ITextEditor getEditor() {
return fTextEditor;
}
/**
* Creates outline presenter.
* @param editor Editor.
* @return Presenter with outline view.
*/
public IInformationPresenter getOutlinePresenter(CEditor editor)
{
final IInformationControlCreator outlineControlCreator = getOutlineContolCreator(editor);
public IInformationPresenter getOutlinePresenter(ISourceViewer sourceViewer) {
final IInformationControlCreator outlineControlCreator = getOutlineContolCreator();
final InformationPresenter presenter = new InformationPresenter(outlineControlCreator);
presenter.setDocumentPartitioning(getConfiguredDocumentPartitioning(null));
presenter.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
final IInformationProvider provider = new CElementContentProvider(getEditor());
presenter.setInformationProvider(provider, IDocument.DEFAULT_CONTENT_TYPE);
presenter.setInformationProvider(provider, ICPartitions.C_MULTI_LINE_COMMENT);
@ -177,30 +255,40 @@ public class CSourceViewerConfiguration extends TextSourceViewerConfiguration {
return presenter;
}
/**
* Initializes the scanners.
*/
private void initializeScanners() {
Assert.isTrue(isNewSetup());
fCppCodeScanner= new CppCodeScanner(getColorManager(), fPreferenceStore);
fCCodeScanner= new CppCodeScanner(getColorManager(), fPreferenceStore);
fMultilineCommentScanner= new CCommentScanner(getColorManager(), fPreferenceStore, ICColorConstants.C_MULTI_LINE_COMMENT);
fSinglelineCommentScanner= new CCommentScanner(getColorManager(), fPreferenceStore, ICColorConstants.C_SINGLE_LINE_COMMENT);
fStringScanner= new SingleTokenCScanner(getColorManager(), fPreferenceStore, ICColorConstants.C_STRING);
fCppPreprocessorScanner= new CPreprocessorScanner(fColorManager, fPreferenceStore, true);
fCPreprocessorScanner= new CPreprocessorScanner(fColorManager, fPreferenceStore, false);
}
/**
* @see org.eclipse.jface.text.source.SourceViewerConfiguration#getPresentationReconciler(org.eclipse.jface.text.source.ISourceViewer)
*/
public IPresentationReconciler getPresentationReconciler(ISourceViewer sourceViewer) {
CPresentationReconciler reconciler= new CPresentationReconciler();
reconciler.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
RuleBasedScanner scanner = null;
ILanguage language= null;
if(sourceViewer instanceof CSourceViewer) {
language = ((CSourceViewer)sourceViewer).getLanguage();
ILanguage language = getLanguage();
if (language instanceof GPPLanguage) {
scanner = fTextTools.getCppCodeScanner();
scanner = fCppCodeScanner;
} else if (language instanceof GCCLanguage) {
scanner = fTextTools.getCCodeScanner();
scanner = fCCodeScanner;
} else if (language != null) {
ILanguageUI languageUI = (ILanguageUI)language.getAdapter(ILanguageUI.class);
if (languageUI != null)
scanner = languageUI.getCodeScanner();
}
}
if (scanner == null) {
scanner= fTextTools.getCCodeScanner();
scanner= fCppCodeScanner;
}
DefaultDamagerRepairer dr= new DefaultDamagerRepairer(scanner);
@ -231,7 +319,7 @@ public class CSourceViewerConfiguration extends TextSourceViewerConfiguration {
} else if (language instanceof GCCLanguage) {
dr= new DefaultDamagerRepairer(getCPreprocessorScanner());
} else {
dr= null;
dr= new DefaultDamagerRepairer(getCppPreprocessorScanner());
}
if (dr != null) {
reconciler.setDamager(new PartitionDamager(), ICPartitions.C_PREPROCESSOR);
@ -270,10 +358,10 @@ public class CSourceViewerConfiguration extends TextSourceViewerConfiguration {
* @see SourceViewerConfiguration#getReconciler(ISourceViewer)
*/
public IReconciler getReconciler(ISourceViewer sourceViewer) {
if (fEditor != null && fEditor.isEditable()) {
if (fTextEditor != null && fTextEditor.isEditable()) {
//Delay changed and non-incremental reconciler used due to
//PR 130089
MonoReconciler reconciler= new MonoReconciler(new CReconcilingStrategy(fEditor), false);
MonoReconciler reconciler= new MonoReconciler(new CReconcilingStrategy(fTextEditor), false);
reconciler.setDelay(500);
return reconciler;
}
@ -287,8 +375,8 @@ public class CSourceViewerConfiguration extends TextSourceViewerConfiguration {
String partitioning= getConfiguredDocumentPartitioning(sourceViewer);
if (ICPartitions.C_MULTI_LINE_COMMENT.equals(contentType))
return new IAutoEditStrategy[] { new CCommentAutoIndentStrategy() };
// else if (ICPartitions.C_STRING.equals(contentType))
// return new IAutoEditStrategy[] { new SmartSemicolonAutoEditStrategy(partitioning), new JavaStringAutoIndentStrategy(partitioning) };
else if (ICPartitions.C_STRING.equals(contentType))
return new IAutoEditStrategy[] { /*new SmartSemicolonAutoEditStrategy(partitioning),*/ new CStringAutoIndentStrategy(partitioning, getProject()) };
else
return new IAutoEditStrategy[] { new CAutoIndentStrategy(partitioning, getProject()) };
}
@ -315,14 +403,22 @@ public class CSourceViewerConfiguration extends TextSourceViewerConfiguration {
Vector vector= new Vector();
// prefix[0] is either '\t' or ' ' x tabWidth, depending on useSpaces
int tabWidth= getTabWidth(sourceViewer);
boolean useSpaces= getPreferenceStore().getBoolean(CEditor.SPACES_FOR_TABS);
for (int i= 0; i <= tabWidth; i++) {
ICProject project= getProject();
final int tabWidth= CodeFormatterUtil.getTabWidth(project);
final int indentWidth= CodeFormatterUtil.getIndentWidth(project);
int spaceEquivalents= Math.min(tabWidth, indentWidth);
boolean useSpaces;
if (project == null)
useSpaces= CCorePlugin.SPACE.equals(CCorePlugin.getOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR)) || tabWidth > indentWidth;
else
useSpaces= CCorePlugin.SPACE.equals(project.getOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, true)) || tabWidth > indentWidth;
for (int i= 0; i <= spaceEquivalents; i++) {
StringBuffer prefix= new StringBuffer();
if (useSpaces) {
for (int j= 0; j + i < tabWidth; j++)
for (int j= 0; j + i < spaceEquivalents; j++)
prefix.append(' ');
if (i != 0)
@ -331,7 +427,7 @@ public class CSourceViewerConfiguration extends TextSourceViewerConfiguration {
for (int j= 0; j < i; j++)
prefix.append(' ');
if (i != tabWidth)
if (i != spaceEquivalents)
prefix.append('\t');
}
@ -362,6 +458,13 @@ public class CSourceViewerConfiguration extends TextSourceViewerConfiguration {
return element.getCProject();
}
/*
* @see SourceViewerConfiguration#getTabWidth(ISourceViewer)
*/
public int getTabWidth(ISourceViewer sourceViewer) {
return CodeFormatterUtil.getTabWidth(getProject());
}
/**
* @see SourceViewerConfiguration#getAnnotationHover(ISourceViewer)
*/
@ -369,8 +472,6 @@ public class CSourceViewerConfiguration extends TextSourceViewerConfiguration {
return new CAnnotationHover();
}
/*
* @see SourceViewerConfiguration#getConfiguredTextHoverStateMasks(ISourceViewer, String)
* @since 2.1
@ -447,12 +548,14 @@ public class CSourceViewerConfiguration extends TextSourceViewerConfiguration {
formatter.setMasterStrategy(new CFormattingStrategy());
return formatter;
}
public boolean affectsBehavior(PropertyChangeEvent event) {
return fTextTools.affectsBehavior(event);
return fCppCodeScanner.affectsBehavior(event)
|| fMultilineCommentScanner.affectsBehavior(event)
|| fSinglelineCommentScanner.affectsBehavior(event)
|| fStringScanner.affectsBehavior(event)
|| fCppPreprocessorScanner.affectsBehavior(event);
}
/**
@ -469,6 +572,13 @@ public class CSourceViewerConfiguration extends TextSourceViewerConfiguration {
return CUIPlugin.getDefault().getPreferenceStore();
}
/**
* @return <code>true</code> iff the new setup without text tools is in use.
*/
private boolean isNewSetup() {
return fTextTools == null;
}
/*
* @see SourceViewerConfiguration#getHoverControlCreator(ISourceViewer)
* @since 2.0
@ -477,7 +587,6 @@ public class CSourceViewerConfiguration extends TextSourceViewerConfiguration {
return getInformationControlCreator(sourceViewer, true);
}
public IInformationControlCreator getInformationControlCreator(ISourceViewer sourceViewer, final boolean cutDown) {
return new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
@ -496,6 +605,51 @@ public class CSourceViewerConfiguration extends TextSourceViewerConfiguration {
return super.getInformationPresenter(sourceViewer);
}
/**
* Determines whether the preference change encoded by the given event
* changes the behavior of one of its contained components.
*
* @param event the event to be investigated
* @return <code>true</code> if event causes a behavioral change
*/
public boolean affectsTextPresentation(PropertyChangeEvent event) {
return fCppCodeScanner.affectsBehavior(event)
|| fCCodeScanner.affectsBehavior(event)
|| fMultilineCommentScanner.affectsBehavior(event)
|| fSinglelineCommentScanner.affectsBehavior(event)
|| fStringScanner.affectsBehavior(event)
|| fCppPreprocessorScanner.affectsBehavior(event);
}
/**
* Adapts the behavior of the contained components to the change
* encoded in the given event.
* <p>
* Clients are not allowed to call this method if the old setup with
* text tools is in use.
* </p>
*
* @param event the event to which to adapt
* @see CSourceViewerConfiguration#CSourceViewerConfiguration(IColorManager, IPreferenceStore, ITextEditor, String)
*/
public void handlePropertyChangeEvent(PropertyChangeEvent event) {
Assert.isTrue(isNewSetup());
if (fCppCodeScanner.affectsBehavior(event))
fCppCodeScanner.adaptToPreferenceChange(event);
if (fCCodeScanner.affectsBehavior(event))
fCCodeScanner.adaptToPreferenceChange(event);
if (fMultilineCommentScanner.affectsBehavior(event))
fMultilineCommentScanner.adaptToPreferenceChange(event);
if (fSinglelineCommentScanner.affectsBehavior(event))
fSinglelineCommentScanner.adaptToPreferenceChange(event);
if (fStringScanner.affectsBehavior(event))
fStringScanner.adaptToPreferenceChange(event);
if (fCppPreprocessorScanner.affectsBehavior(event))
fCppPreprocessorScanner.adaptToPreferenceChange(event);
if (fCPreprocessorScanner.affectsBehavior(event))
fCPreprocessorScanner.adaptToPreferenceChange(event);
}
/*
* @see org.eclipse.jface.text.source.SourceViewerConfiguration#getHyperlinkDetectors(org.eclipse.jface.text.source.ISourceViewer)
* @since 3.1
@ -506,12 +660,12 @@ public class CSourceViewerConfiguration extends TextSourceViewerConfiguration {
IHyperlinkDetector[] inheritedDetectors= super.getHyperlinkDetectors(sourceViewer);
if (fEditor == null)
if (fTextEditor == null)
return inheritedDetectors;
int inheritedDetectorsLength= inheritedDetectors != null ? inheritedDetectors.length : 0;
IHyperlinkDetector[] detectors= new IHyperlinkDetector[inheritedDetectorsLength + 1];
detectors[0]= new CElementHyperlinkDetector(fEditor);
detectors[0]= new CElementHyperlinkDetector(fTextEditor);
for (int i= 0; i < inheritedDetectorsLength; i++) {
detectors[i+1]= inheritedDetectors[i];
}
@ -523,26 +677,24 @@ public class CSourceViewerConfiguration extends TextSourceViewerConfiguration {
* @see org.eclipse.jface.text.source.SourceViewerConfiguration#getConfiguredDocumentPartitioning(org.eclipse.jface.text.source.ISourceViewer)
*/
public String getConfiguredDocumentPartitioning(ISourceViewer sourceViewer) {
return fTextTools.getDocumentPartitioning();
if (fDocumentPartitioning != null)
return fDocumentPartitioning;
return super.getConfiguredDocumentPartitioning(sourceViewer);
}
/**
* Creates control for outline presentation in editor.
* @param editor Editor.
* @return Control.
*/
private IInformationControlCreator getOutlineContolCreator(final CEditor editor)
{
final IInformationControlCreator conrolCreator = new IInformationControlCreator()
{
private IInformationControlCreator getOutlineContolCreator() {
final IInformationControlCreator conrolCreator = new IInformationControlCreator() {
/**
* @see org.eclipse.jface.text.IInformationControlCreator#createInformationControl(org.eclipse.swt.widgets.Shell)
*/
public IInformationControl createInformationControl(Shell parent)
{
public IInformationControl createInformationControl(Shell parent) {
int shellStyle= SWT.RESIZE;
int treeStyle= SWT.V_SCROLL | SWT.H_SCROLL;
return new COutlineInformationControl(editor, parent, shellStyle, treeStyle);
return new COutlineInformationControl(parent, shellStyle, treeStyle);
}
};
return conrolCreator;
@ -563,13 +715,42 @@ public class CSourceViewerConfiguration extends TextSourceViewerConfiguration {
return settings;
}
/**
* Adapt to the given preference change event.
*
* @param event
*/
public void handlePropertyChangeEvent(PropertyChangeEvent event) {
fTextTools.adaptToPreferenceChange(event);
protected ILanguage getLanguage() {
if (fTextEditor == null) {
return null;
}
ICElement element = CUIPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(fTextEditor.getEditorInput());
if (element instanceof ITranslationUnit) {
try {
return ((ITranslationUnit)element).getLanguage();
} catch (CoreException e) {
CUIPlugin.getDefault().log(e);
}
} else {
// compute the language from the plain editor input
IContentType contentType = null;
IEditorInput input = fTextEditor.getEditorInput();
IFile file = ResourceUtil.getFile(input);
if (file != null) {
contentType = CCorePlugin.getContentType(file.getProject(), file.getName());
} else if (input instanceof IPathEditorInput) {
IPath path = ((IPathEditorInput)input).getPath();
contentType = CCorePlugin.getContentType(path.lastSegment());
} else {
ILocationProvider locationProvider = (ILocationProvider)input.getAdapter(ILocationProvider.class);
if (locationProvider != null) {
IPath path = locationProvider.getPath(input);
contentType = CCorePlugin.getContentType(path.lastSegment());
}
}
if (contentType != null) {
try {
return LanguageManager.getInstance().getLanguage(contentType);
} catch (CoreException exc) {
CUIPlugin.getDefault().log(exc.getStatus());
}
}
}
return null;
}
}

View file

@ -0,0 +1,187 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.ui.text;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultIndentLineAutoEditStrategy;
import org.eclipse.jface.text.DocumentCommand;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.texteditor.ITextEditorExtension3;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.ui.PreferenceConstants;
/**
* Auto indent strategy for C strings
*/
public class CStringAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy {
private String fPartitioning;
private final ICProject fProject;
/**
* The input string doesn't contain any line delimiter.
*
* @param inputString the given input string
* @return the displayable string.
*/
private String displayString(String inputString, CharSequence indentation, String delimiter) {
int length = inputString.length();
StringBuffer buffer = new StringBuffer(length);
java.util.StringTokenizer tokenizer = new java.util.StringTokenizer(inputString, "\n\r", true); //$NON-NLS-1$
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
if (token.equals("\r")) { //$NON-NLS-1$
buffer.append("\\r"); //$NON-NLS-1$
if (tokenizer.hasMoreTokens()) {
token = tokenizer.nextToken();
if (token.equals("\n")) { //$NON-NLS-1$
buffer.append("\\n"); //$NON-NLS-1$
buffer.append("\"" + delimiter); //$NON-NLS-1$
buffer.append(indentation);
buffer.append("\""); //$NON-NLS-1$
continue;
} else {
buffer.append("\"" + delimiter); //$NON-NLS-1$
buffer.append(indentation);
buffer.append("\""); //$NON-NLS-1$
}
} else {
continue;
}
} else if (token.equals("\n")) { //$NON-NLS-1$
buffer.append("\\n"); //$NON-NLS-1$
buffer.append("\"" + delimiter); //$NON-NLS-1$
buffer.append(indentation);
buffer.append("\""); //$NON-NLS-1$
continue;
}
StringBuffer tokenBuffer = new StringBuffer();
for (int i = 0; i < token.length(); i++){
char c = token.charAt(i);
switch (c) {
case '\r' :
tokenBuffer.append("\\r"); //$NON-NLS-1$
break;
case '\n' :
tokenBuffer.append("\\n"); //$NON-NLS-1$
break;
case '\b' :
tokenBuffer.append("\\b"); //$NON-NLS-1$
break;
case '\t' :
// keep tabs verbatim
tokenBuffer.append("\t"); //$NON-NLS-1$
break;
case '\f' :
tokenBuffer.append("\\f"); //$NON-NLS-1$
break;
case '\"' :
tokenBuffer.append("\\\""); //$NON-NLS-1$
break;
case '\'' :
tokenBuffer.append("\\'"); //$NON-NLS-1$
break;
case '\\' :
tokenBuffer.append("\\\\"); //$NON-NLS-1$
break;
default :
tokenBuffer.append(c);
}
}
buffer.append(tokenBuffer);
}
return buffer.toString();
}
/**
* Creates a new C string auto indent strategy for the given document partitioning.
*
* @param partitioning the document partitioning
*/
public CStringAutoIndentStrategy(String partitioning, ICProject project) {
super();
fPartitioning = partitioning;
fProject = project;
}
private boolean isLineDelimiter(IDocument document, String text) {
String[] delimiters= document.getLegalLineDelimiters();
if (delimiters != null)
return TextUtilities.equals(delimiters, text) > -1;
return false;
}
private String getModifiedText(String string, CharSequence indentation, String delimiter) {
return displayString(string, indentation, delimiter);
}
private void indentStringAfterNewLine(IDocument document, DocumentCommand command) throws BadLocationException {
ITypedRegion partition= TextUtilities.getPartition(document, fPartitioning, command.offset, true);
int offset= partition.getOffset();
int length= partition.getLength();
if (command.offset == offset + length && document.getChar(offset + length - 1) == '\"')
return;
CHeuristicScanner scanner = new CHeuristicScanner(document);
CIndenter indenter = new CIndenter(document, scanner, fProject);
StringBuffer indentation = indenter.computeContinuationLineIndentation(offset);
if (indentation == null)
indentation = new StringBuffer();
String delimiter= TextUtilities.getDefaultLineDelimiter(document);
IPreferenceStore preferenceStore= CUIPlugin.getDefault().getPreferenceStore();
if (isLineDelimiter(document, command.text))
command.text= "\"" + command.text + indentation + "\""; //$NON-NLS-1$//$NON-NLS-2$
else if (command.text.length() > 1 && preferenceStore.getBoolean(PreferenceConstants.EDITOR_ESCAPE_STRINGS))
command.text= getModifiedText(command.text, indentation, delimiter);
}
private boolean isSmartMode() {
IWorkbenchPage page= CUIPlugin.getActivePage();
if (page != null) {
IEditorPart part= page.getActiveEditor();
if (part instanceof ITextEditorExtension3) {
ITextEditorExtension3 extension= (ITextEditorExtension3) part;
return extension.getInsertMode() == ITextEditorExtension3.SMART_INSERT;
}
}
return false;
}
/*
* @see org.eclipse.jface.text.IAutoIndentStrategy#customizeDocumentCommand(IDocument, DocumentCommand)
*/
public void customizeDocumentCommand(IDocument document, DocumentCommand command) {
try {
if (command.length != 0 || command.text == null)
return;
IPreferenceStore preferenceStore= CUIPlugin.getDefault().getPreferenceStore();
if (preferenceStore.getBoolean(PreferenceConstants.EDITOR_WRAP_STRINGS) && isSmartMode()) {
indentStringAfterNewLine(document, command);
}
} catch (BadLocationException e) {
}
}
}

View file

@ -0,0 +1,141 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.ui.text;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.IAutoEditStrategy;
import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.formatter.IContentFormatter;
import org.eclipse.jface.text.hyperlink.IHyperlinkDetector;
import org.eclipse.jface.text.information.IInformationPresenter;
import org.eclipse.jface.text.source.IAnnotationHover;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.ui.texteditor.ITextEditor;
/**
* A simple {@linkplain org.eclipse.cdt.internal.ui.text.CSourceViewerConfiguration C source viewer configuration}.
* <p>
* This simple source viewer configuration basically provides syntax coloring
* and disables all other features like code assist, quick outlines, hyperlinking, etc.
* </p>
*/
public class SimpleCSourceViewerConfiguration extends CSourceViewerConfiguration {
private boolean fConfigureFormatter;
/**
* Creates a new C source viewer configuration for viewers in the given editor
* using the given preference store, the color manager and the specified document partitioning.
*
* @param colorManager the color manager
* @param preferenceStore the preference store, can be read-only
* @param editor the editor in which the configured viewer(s) will reside, or <code>null</code> if none
* @param partitioning the document partitioning for this configuration, or <code>null</code> for the default partitioning
* @param configureFormatter <code>true</code> if a content formatter should be configured
*/
public SimpleCSourceViewerConfiguration(IColorManager colorManager, IPreferenceStore preferenceStore, ITextEditor editor, String partitioning, boolean configureFormatter) {
super(colorManager, preferenceStore, editor, partitioning);
fConfigureFormatter= configureFormatter;
}
/*
* @see org.eclipse.jface.text.source.SourceViewerConfiguration#getAutoEditStrategies(org.eclipse.jface.text.source.ISourceViewer, java.lang.String)
*/
public IAutoEditStrategy[] getAutoEditStrategies(ISourceViewer sourceViewer, String contentType) {
return null;
}
/*
* @see SourceViewerConfiguration#getAnnotationHover(ISourceViewer)
*/
public IAnnotationHover getAnnotationHover(ISourceViewer sourceViewer) {
return null;
}
/*
* @see SourceViewerConfiguration#getOverviewRulerAnnotationHover(ISourceViewer)
*/
public IAnnotationHover getOverviewRulerAnnotationHover(ISourceViewer sourceViewer) {
return null;
}
/*
* @see SourceViewerConfiguration#getConfiguredTextHoverStateMasks(ISourceViewer, String)
*/
public int[] getConfiguredTextHoverStateMasks(ISourceViewer sourceViewer, String contentType) {
return null;
}
/*
* @see SourceViewerConfiguration#getTextHover(ISourceViewer, String, int)
*/
public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType, int stateMask) {
return null;
}
/*
* @see SourceViewerConfiguration#getTextHover(ISourceViewer, String)
*/
public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType) {
return null;
}
/*
* @see SourceViewerConfiguration#getContentFormatter(ISourceViewer)
*/
public IContentFormatter getContentFormatter(ISourceViewer sourceViewer) {
if (fConfigureFormatter)
return super.getContentFormatter(sourceViewer);
else
return null;
}
/*
* @see SourceViewerConfiguration#getInformationControlCreator(ISourceViewer)
*/
public IInformationControlCreator getInformationControlCreator(ISourceViewer sourceViewer) {
return null;
}
/*
* @see SourceViewerConfiguration#getInformationPresenter(ISourceViewer)
*/
public IInformationPresenter getInformationPresenter(ISourceViewer sourceViewer) {
return null;
}
/*
* @see org.eclipse.cdt.ui.text.CSourceViewerConfiguration#getOutlinePresenter(org.eclipse.jface.text.source.ISourceViewer, boolean)
*/
public IInformationPresenter getOutlinePresenter(ISourceViewer sourceViewer, boolean doCodeResolve) {
return null;
}
/*
* @see org.eclipse.cdt.ui.text.CSourceViewerConfiguration#getHierarchyPresenter(org.eclipse.jface.text.source.ISourceViewer, boolean)
*/
public IInformationPresenter getHierarchyPresenter(ISourceViewer sourceViewer, boolean doCodeResolve) {
return null;
}
/*
* @see org.eclipse.jface.text.source.SourceViewerConfiguration#getHyperlinkDetectors(org.eclipse.jface.text.source.ISourceViewer)
*/
public IHyperlinkDetector[] getHyperlinkDetectors(ISourceViewer sourceViewer) {
return null;
}
}

View file

@ -41,13 +41,15 @@ public interface Symbols {
int TokenRETURN= 1018;
int TokenSTATIC= 1019;
int TokenSWITCH= 1020;
// int TokenFINALLY= 1021;
// int TokenSYNCHRONIZED= 1022;
int TokenGOTO= 1023;
int TokenDEFAULT= 1024;
int TokenNEW= 1025;
int TokenCLASS= 1026;
// int TokenINTERFACE= 1027;
int TokenENUM= 1028;
int TokenGOTO= 1021;
int TokenDEFAULT= 1022;
int TokenPRIVATE= 1023;
int TokenPROTECTED= 1024;
int TokenPUBLIC= 1025;
int TokenNEW= 1026;
int TokenDELETE= 1027;
int TokenCLASS= 1028;
int TokenSTRUCT= 1029;
int TokenENUM= 1030;
int TokenIDENT= 2000;
}

View file

@ -0,0 +1,52 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.ui.text.comment;
import org.eclipse.jface.text.formatter.FormattingContext;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants;
/**
* Formatting context for the comment formatter.
*
* @since 4.0
*/
public class CommentFormattingContext extends FormattingContext {
/*
* @see org.eclipse.jface.text.formatter.IFormattingContext#getPreferenceKeys()
*/
public String[] getPreferenceKeys() {
return new String[] {
DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT,
DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_HEADER,
DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_SOURCE,
DefaultCodeFormatterConstants.FORMATTER_COMMENT_LINE_LENGTH,
DefaultCodeFormatterConstants.FORMATTER_COMMENT_CLEAR_BLANK_LINES};
}
/*
* @see org.eclipse.jface.text.formatter.IFormattingContext#isBooleanPreference(java.lang.String)
*/
public boolean isBooleanPreference(String key) {
return !key.equals(DefaultCodeFormatterConstants.FORMATTER_COMMENT_LINE_LENGTH);
}
/*
* @see org.eclipse.jface.text.formatter.IFormattingContext#isIntegerPreference(java.lang.String)
*/
public boolean isIntegerPreference(String key) {
return key.equals(DefaultCodeFormatterConstants.FORMATTER_COMMENT_LINE_LENGTH);
}
}

View file

@ -147,27 +147,36 @@ public class Strings {
*
* @param line the text line
* @param tabWidth the width of the '\t' character.
* @return the indentation level of the given string
*
* @deprecated use {@link #computeIndent(String, int, int)} instead.
*/
public static int computeIndent(String line, int tabWidth) {
return computeIndent(line, tabWidth, tabWidth);
}
/**
* Returns the indent level of the given string.
*
* @param line the text line
* @param tabWidth the width of the '\t' character.
* @param indentSize the space-equivalent of an indent level
* @return the indentation level of the given string
*/
public static int computeIndent(String line, int tabWidth, int indentSize) {
int result= 0;
int blanks= 0;
int size= line.length();
for (int i= 0; i < size; i++) {
char c= line.charAt(i);
if (c == '\t') {
result++;
blanks= 0;
result+= tabWidth;
} else if (isIndentChar(c)) {
blanks++;
if (blanks == tabWidth) {
result++;
blanks= 0;
}
} else {
return result;
break;
}
}
return result;
return result / indentSize;
}
/**

View file

@ -8,7 +8,6 @@
* Contributors:
* IBM Corporation - initial API and implementation
* QNX Software System
* Anton Leherbauer (Wind River Systems)
*******************************************************************************/
package org.eclipse.cdt.ui;
@ -596,6 +595,15 @@ public class PreferenceConstants {
*/
public final static String EDITOR_CLOSE_BRACKETS= "closeBrackets"; //$NON-NLS-1$
/**
* A named preference that controls whether the 'close angular brackets' feature is
* enabled.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_CLOSE_ANGULAR_BRACKETS= "closeAngularBrackets"; //$NON-NLS-1$
/**
* A named preference that controls whether the 'close braces' feature is
* enabled.
@ -605,6 +613,22 @@ public class PreferenceConstants {
*/
public final static String EDITOR_CLOSE_BRACES= "closeBraces"; //$NON-NLS-1$
/**
* A named preference that controls whether the 'smart paste' feature is
* enabled.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_SMART_PASTE= "smartPaste"; //$NON-NLS-1$
/**
* A named preference that controls the smart tab behavior.
* <p>
* Value is of type <code>Boolean</code>.
*/
public static final String EDITOR_SMART_TAB= "smart_tab"; //$NON-NLS-1$
/**
* The id of the best match hover contributed for extension point
* <code>org.eclipse.cdt.ui.textHovers</code>.
@ -858,6 +882,15 @@ public class PreferenceConstants {
*/
public static final String TEMPLATES_USE_CODEFORMATTER= "org.eclipse.cdt.ui.text.templates.format"; //$NON-NLS-1$
/**
* A named preference that controls which profile is used by the code formatter.
* <p>
* Value is of type <code>String</code>.
* </p>
*
* @since 4.0
*/
public static final String FORMATTER_PROFILE = "formatter_profile"; //$NON-NLS-1$
/**
* Preference key for whether to ensure a newline at the end of files when saving.
@ -1049,7 +1082,10 @@ public class PreferenceConstants {
store.setDefault(PreferenceConstants.EDITOR_CLOSE_STRINGS, true);
store.setDefault(PreferenceConstants.EDITOR_CLOSE_BRACKETS, true);
store.setDefault(PreferenceConstants.EDITOR_CLOSE_ANGULAR_BRACKETS, true);
store.setDefault(PreferenceConstants.EDITOR_CLOSE_BRACES, true);
store.setDefault(PreferenceConstants.EDITOR_SMART_PASTE, true);
store.setDefault(PreferenceConstants.EDITOR_SMART_TAB, true);
store.setDefault(PreferenceConstants.EDITOR_WRAP_STRINGS, true);
store.setDefault(PreferenceConstants.EDITOR_ESCAPE_STRINGS, false);

View file

@ -10,7 +10,6 @@
*******************************************************************************/
package org.eclipse.cdt.utils.ui.controls;
import java.util.StringTokenizer;
import org.eclipse.jface.viewers.CellEditor;
@ -56,7 +55,7 @@ public class ControlFactory {
*
* @param parent the parent of the new composite
* @param numColumns the number of columns for the new composite
* @return the newly-created coposite
* @return the newly-created composite
*/
public static Composite createComposite(Composite parent, int numColumns) {
return createCompositeEx(parent, numColumns, GridData.FILL_HORIZONTAL);
@ -68,10 +67,11 @@ public class ControlFactory {
* @param parent the parent of the new composite
* @param numColumns the number of columns for the new composite
* @param layoutMode - GridData modes that should be applied to this control
* @return the newly-created coposite
* @return the newly-created composite
*/
public static Composite createCompositeEx(Composite parent, int numColumns, int layoutMode) {
Composite composite = new Composite(parent, SWT.NULL);
composite.setFont(parent.getFont());
composite.setLayout(new GridLayout(numColumns, true));
composite.setLayoutData(new GridData(layoutMode));
@ -108,6 +108,7 @@ public class ControlFactory {
separator.setLayoutData(data);
return separator;
}
/**
* Creates a spacer control.
* @param parent The parent composite
@ -115,6 +116,7 @@ public class ControlFactory {
public static Control createEmptySpace(Composite parent) {
return createEmptySpace(parent, 1);
}
/**
* Creates a spacer control with the given span.
* The composite is assumed to have <code>MGridLayout</code> as
@ -137,7 +139,6 @@ public class ControlFactory {
/**
* Creates an new label (basic method)
*
*
* @param parent parent object
* @param text the label text
* @param widthHint - recommended widget width
@ -148,6 +149,7 @@ public class ControlFactory {
public static Label createLabel(Composite parent, String text, int widthHint, int heightHint, int style) {
Label label = new Label(parent, style);
label.setFont(parent.getFont());
label.setText(text);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = 1;
@ -187,7 +189,6 @@ public class ControlFactory {
return label;
}
/**
* Creates an new Wrapped label
*
@ -202,7 +203,6 @@ public class ControlFactory {
return createLabel(parent, text, widthHint, heightHint, SWT.LEFT | SWT.WRAP);
}
/**
* Creates an new checkbox instance and sets the default
* layout data.
@ -213,6 +213,7 @@ public class ControlFactory {
*/
public static Button createCheckBox(Composite group, String label) {
Button button = new Button(group, SWT.CHECK | SWT.LEFT);
button.setFont(group.getFont());
button.setText(label);
GridData data = new GridData();
button.setLayoutData(data);
@ -231,6 +232,7 @@ public class ControlFactory {
*/
public static Button createCheckBoxEx(Composite group, String label, int style) {
Button button = new Button(group, SWT.CHECK | style);
button.setFont(group.getFont());
button.setText(label);
GridData data = new GridData();
button.setLayoutData(data);
@ -250,6 +252,7 @@ public class ControlFactory {
*/
public static Button createRadioButton(Composite group, String label, String value, SelectionListener listener) {
Button button = new Button(group, SWT.RADIO | SWT.LEFT);
button.setFont(group.getFont());
button.setText(label);
button.setData((null == value) ? label : value);
GridData data = new GridData(GridData.FILL_HORIZONTAL);
@ -271,6 +274,7 @@ public class ControlFactory {
*/
public static Button createPushButton(Composite parent, String label) {
Button button = new Button(parent, SWT.PUSH);
button.setFont(parent.getFont());
button.setText(label);
// button.addSelectionListener(this);
GridData data = new GridData();
@ -279,7 +283,6 @@ public class ControlFactory {
return button;
}
/**
* Create a text field specific for this application
*
@ -312,6 +315,7 @@ public class ControlFactory {
*/
public static Group createGroup(Composite parent, String label, int nColumns) {
Group group = new Group(parent, SWT.NONE);
group.setFont(parent.getFont());
group.setText(label);
GridLayout layout = new GridLayout();
layout.numColumns = nColumns;
@ -321,7 +325,6 @@ public class ControlFactory {
return group;
}
/**
* Create a List box
*
@ -332,6 +335,7 @@ public class ControlFactory {
*/
public static List createList(Composite parent, String strdata, String selData) {
List list = new List(parent, SWT.SINGLE);
list.setFont(parent.getFont());
GridData data = new GridData();
list.setLayoutData(data);
StringTokenizer st = new StringTokenizer(strdata, ","); //$NON-NLS-1$
@ -340,9 +344,9 @@ public class ControlFactory {
if (selData == null) {
if (list.getItemCount() > 0)
list.select(0);
}
else
} else {
selectList(list, selData);
}
return list;
}
@ -353,9 +357,6 @@ public class ControlFactory {
list.select(n_sel);
}
/**
* Create this group's list viewer.
*/
@ -371,7 +372,6 @@ public class ControlFactory {
return listViewer;
}
/**
* Create this group's list viewer.
*/
@ -395,7 +395,6 @@ public class ControlFactory {
column= new TableColumn(table, SWT.NULL);
column.setText(columns[i]);
tableLayout.addColumnData(new ColumnWeightData(colWidths[i], true));
}
table.setLayout(tableLayout);
@ -432,6 +431,7 @@ public class ControlFactory {
int width, int height, int style) {
Table table = new Table(parent, SWT.BORDER | SWT.CHECK);
table.setFont(parent.getFont());
CheckboxTableViewer listViewer = new CheckboxTableViewer(table);
GridData data = new GridData(style);
data.widthHint = width;
@ -444,14 +444,13 @@ public class ControlFactory {
return listViewer;
}
public static CheckboxTableViewer createListViewer(Composite parent,
int width, int height, int style, String[] columns, int[] colWidths) {
CheckboxTableViewer listViewer = createListViewer(parent, null,
width, height, style);
Table table= listViewer.getTable();
table.setFont(parent.getFont());
table.setHeaderVisible(true);
table.setLinesVisible(true);
@ -473,7 +472,6 @@ public class ControlFactory {
return listViewer;
}
/**
* Create a selection combo
*
@ -489,6 +487,7 @@ public class ControlFactory {
public static CCombo createSelectCCombo(Composite parent, String strdata, String selData, int style) {
CCombo combo = new CCombo(parent, style);
combo.setFont(parent.getFont());
GridData data = new GridData(GridData.FILL_HORIZONTAL);
combo.setLayoutData(data);
StringTokenizer st = new StringTokenizer(strdata, ","); //$NON-NLS-1$
@ -497,13 +496,12 @@ public class ControlFactory {
if (selData == null || selData.length() == 0) {
if (combo.getItemCount() > 0)
combo.select(0);
}
else
} else {
selectCCombo(combo, selData);
}
return combo;
}
/**
* Create a selection combo
*
@ -518,6 +516,7 @@ public class ControlFactory {
public static CCombo createSelectCCombo(Composite parent, String[] strdata, String selData, int style) {
CCombo combo = new CCombo(parent, style);
combo.setFont(parent.getFont());
GridData data = new GridData(GridData.FILL_HORIZONTAL);
combo.setLayoutData(data);
for (int i = 0; i < strdata.length; ++i) {
@ -537,15 +536,6 @@ public class ControlFactory {
combo.select(n_sel);
}
/**
* Create a selection combo
*
@ -561,6 +551,7 @@ public class ControlFactory {
public static Combo createSelectCombo(Composite parent, String strdata, String selData, int style) {
Combo combo = new Combo(parent, style);
combo.setFont(parent.getFont());
GridData data = new GridData(GridData.FILL_HORIZONTAL);
combo.setLayoutData(data);
StringTokenizer st = new StringTokenizer(strdata, ","); //$NON-NLS-1$
@ -569,13 +560,12 @@ public class ControlFactory {
if (selData == null || selData.length() == 0) {
if (combo.getItemCount() > 0)
combo.select(0);
}
else
} else {
selectCombo(combo, selData);
}
return combo;
}
/**
* Create a selection combo
*
@ -590,6 +580,7 @@ public class ControlFactory {
public static Combo createSelectCombo(Composite parent, String[] strdata, String selData, int style) {
Combo combo = new Combo(parent, style);
combo.setFont(parent.getFont());
GridData data = new GridData(GridData.FILL_HORIZONTAL);
combo.setLayoutData(data);
for (int i = 0; i < strdata.length; ++i) {
@ -614,16 +605,6 @@ public class ControlFactory {
combo.select(n_sel);
}
/**
* Create a dialog shell, child to the top level workbench shell.
*
@ -637,8 +618,6 @@ public class ControlFactory {
return new Shell( parent, SWT.DIALOG_TRIM );
}
public static Composite insertSpace(Composite parent, int nSpan, int height) {
Composite space = ControlFactory.createCompositeSeparator(parent, parent.getBackground(),
(SWT.DEFAULT != height ? height : 5));
@ -664,5 +643,4 @@ public class ControlFactory {
public static MessageBox createOkCancelDialog( String title, String message ) {
return createDialog( title, message, SWT.OK | SWT.CANCEL | SWT.ICON_INFORMATION );
}
}