示例#1
0
        public override void Initialize()
        {
            base.Initialize();

            IEnumerable <string> types = MonoDevelop.Ide.DesktopService.GetMimeTypeInheritanceChain(CSharpFormatter.MimeType);

            if (base.Document.Project != null && base.Document.Project.Policies != null)
            {
                policy          = base.Document.Project.Policies.Get <CSharpFormattingPolicy> (types);
                textStylePolicy = base.Document.Project.Policies.Get <TextStylePolicy> (types);
            }

            textEditorData = Document.Editor;
            if (textEditorData != null)
            {
                textEditorData.Options.Changed += delegate {
                    policy          = base.Document.Project.Policies.Get <CSharpFormattingPolicy> (types);
                    textStylePolicy = base.Document.Project.Policies.Get <TextStylePolicy> (types);
                    textEditorData.IndentationTracker = new IndentVirtualSpaceManager(
                        textEditorData,
                        new DocumentStateTracker <CSharpIndentEngine> (new CSharpIndentEngine(policy, textStylePolicy), textEditorData)
                        );
                };
                textEditorData.IndentationTracker = new IndentVirtualSpaceManager(
                    textEditorData,
                    new DocumentStateTracker <CSharpIndentEngine> (new CSharpIndentEngine(policy, textStylePolicy), textEditorData)
                    );
            }

            InitTracker();
//			Document.Editor.Paste += HandleTextPaste;
        }
示例#2
0
        public CSharpTextEditorIndentation()
        {
            IEnumerable <string> types = MonoDevelop.Ide.DesktopService.GetMimeTypeInheritanceChain(CSharpFormatter.MimeType);

            policy          = MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy <CSharpFormattingPolicy> (types);
            textStylePolicy = MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy <TextStylePolicy> (types);
        }
示例#3
0
        public CSharpCodeGenerator()
        {
            visitor = new OutputVisitor(this);

            IEnumerable <string> types = MonoDevelop.Ide.DesktopService.GetMimeTypeInheritanceChain(CSharpFormatter.MimeType);

            policy = MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy <CSharpFormattingPolicy> (types);
        }
示例#4
0
        public static string FormatText(CSharpFormattingPolicy policy, TextStylePolicy textPolicy, string input, int startOffset, int endOffset)
        {
            var inputTree = CSharpSyntaxTree.ParseText(input);

            var root   = inputTree.GetRoot();
            var doc    = Formatter.Format(root, new TextSpan(startOffset, endOffset - startOffset), TypeSystemService.Workspace, policy.CreateOptions(textPolicy));
            var result = doc.ToFullString();

            return(result.Substring(startOffset, endOffset + result.Length - input.Length - startOffset));
        }
示例#5
0
 // Constructors
 public CSharpIndentEngine(CSharpFormattingPolicy policy)
 {
     if (policy == null)
     {
         throw new ArgumentNullException("policy");
     }
     this.policy = policy;
     stack       = new IndentStack(this);
     linebuf     = new StringBuilder();
     Reset();
 }
        public CSharpFormattingPolicyPanelWidget()
        {
            // ReSharper disable once DoNotCallOverridableMethodsInConstructor
            this.Build();
            policy              = new CSharpFormattingPolicy();
            buttonEdit.Clicked += HandleButtonEditClicked;

            texteditor.Options    = DefaultSourceEditorOptions.PlainEditor;
            texteditor.IsReadOnly = true;
            texteditor.MimeType   = CSharpFormatter.MimeType;
            scrolledwindow1.AddWithViewport(texteditor);
            ShowAll();
        }
        public CSharpFormattingPolicyPanelWidget()
        {
            this.Build();
            policy              = new CSharpFormattingPolicy();
            buttonEdit.Clicked += HandleButtonEditClicked;

            var options = MonoDevelop.SourceEditor.DefaultSourceEditorOptions.Instance;

            texteditor.Options.FontName             = options.FontName;
            texteditor.Options.ColorScheme          = options.ColorScheme;
            texteditor.Options.ShowFoldMargin       = false;
            texteditor.Options.ShowIconMargin       = false;
            texteditor.Options.ShowLineNumberMargin = false;
            texteditor.Document.ReadOnly            = true;
            texteditor.Document.MimeType            = CSharpFormatter.MimeType;
            scrolledwindow1.Child = texteditor;
            ShowAll();
        }
        public override void Initialize()
        {
            base.Initialize();

            IEnumerable <string> types = MonoDevelop.Ide.DesktopService.GetMimeTypeInheritanceChain(CSharpFormatter.MimeType);

            if (base.Document.Project != null && base.Document.Project.Policies != null)
            {
                policy = base.Document.Project.Policies.Get <CSharpFormattingPolicy> (types);
            }

            textEditorData = Document.Editor;
            if (textEditorData != null)
            {
                textEditorData.VirtualSpaceManager           = new IndentVirtualSpaceManager(textEditorData, new DocumentStateTracker <CSharpIndentEngine> (new CSharpIndentEngine(policy), textEditorData));
                textEditorData.Caret.AllowCaretBehindLineEnd = true;
            }

            InitTracker();
        }
        public static void SetFormatOptions(CSharpOutputVisitor outputVisitor, PolicyContainer policyParent)
        {
            IEnumerable <string> types         = DesktopService.GetMimeTypeInheritanceChain(MimeType);
            TextStylePolicy      currentPolicy = policyParent != null?policyParent.Get <TextStylePolicy> (types) : MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy <TextStylePolicy> (types);

            CSharpFormattingPolicy codePolicy = policyParent != null?policyParent.Get <CSharpFormattingPolicy> (types) : MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy <CSharpFormattingPolicy> (types);

            outputVisitor.Options.IndentationChar = currentPolicy.TabsToSpaces ? ' ' : '\t';
            outputVisitor.Options.TabSize         = currentPolicy.TabWidth;
            outputVisitor.Options.IndentSize      = currentPolicy.TabWidth;
            outputVisitor.Options.EolMarker       = TextStylePolicy.GetEolMarker(currentPolicy.EolMarker);

            CodeFormatDescription descr = CSharpFormattingPolicyPanel.CodeFormatDescription;
            Type optionType             = outputVisitor.Options.GetType();

            foreach (CodeFormatOption option in descr.AllOptions)
            {
                KeyValuePair <string, string> val = descr.GetValue(codePolicy, option);
                PropertyInfo info = optionType.GetProperty(option.Name);
                if (info == null)
                {
                    System.Console.WriteLine("option : " + option.Name + " not found.");
                    continue;
                }
                object cval = null;
                if (info.PropertyType.IsEnum)
                {
                    cval = Enum.Parse(info.PropertyType, val.Key);
                }
                else if (info.PropertyType == typeof(bool))
                {
                    cval = Convert.ToBoolean(val.Key);
                }
                else
                {
                    cval = Convert.ChangeType(val.Key, info.PropertyType);
                }
                //System.Console.WriteLine("set " + option.Name + " to " + cval);
                info.SetValue(outputVisitor.Options, cval, null);
            }
        }
示例#10
0
        public static string FormatText(CSharpFormattingPolicy policy, TextStylePolicy textPolicy, string mimeType, string input, int startOffset, int endOffset)
        {
            var data = new TextEditorData();

            data.Document.SuppressHighlightUpdate = true;
            data.Document.MimeType = mimeType;
            data.Document.FileName = "toformat.cs";
            if (textPolicy != null)
            {
                data.Options.TabsToSpaces    = textPolicy.TabsToSpaces;
                data.Options.TabSize         = textPolicy.TabWidth;
                data.Options.IndentationSize = textPolicy.IndentWidth;
                data.Options.IndentStyle     = textPolicy.RemoveTrailingWhitespace ? IndentStyle.Virtual : IndentStyle.Smart;
            }
            data.Text = input;

            // System.Console.WriteLine ("-----");
            // System.Console.WriteLine (data.Text.Replace (" ", ".").Replace ("\t", "->"));
            // System.Console.WriteLine ("-----");

            var  parser          = new CSharpParser();
            var  compilationUnit = parser.Parse(data);
            bool hadErrors       = parser.HasErrors;

            if (hadErrors)
            {
                //				foreach (var e in parser.ErrorReportPrinter.Errors)
                //					Console.WriteLine (e.Message);
                return(input.Substring(startOffset, Math.Max(0, Math.Min(endOffset, input.Length) - startOffset)));
            }

            var originalVersion = data.Document.Version;

            var textEditorOptions = data.CreateNRefactoryTextEditorOptions();
            var formattingVisitor = new ICSharpCode.NRefactory.CSharp.CSharpFormatter(
                policy.CreateOptions(),
                textEditorOptions
                )
            {
                FormattingMode = FormattingMode.Intrusive
            };

            var changes = formattingVisitor.AnalyzeFormatting(data.Document, compilationUnit);

            try {
                changes.ApplyChanges(startOffset, endOffset - startOffset);
            } catch (Exception e) {
                LoggingService.LogError("Error in code formatter", e);
                return(input.Substring(startOffset, Math.Max(0, Math.Min(endOffset, input.Length) - startOffset)));
            }

            // check if the formatter has produced errors
            parser = new CSharpParser();
            parser.Parse(data);
            if (parser.HasErrors)
            {
                LoggingService.LogError("C# formatter produced source code errors. See console for output.");
                return(input.Substring(startOffset, Math.Max(0, Math.Min(endOffset, input.Length) - startOffset)));
            }

            var currentVersion = data.Document.Version;

            string result = data.GetTextBetween(startOffset, originalVersion.MoveOffsetTo(currentVersion, endOffset));

            data.Dispose();
            return(result);
        }
 public void SetPolicy(CSharpFormattingPolicy cSharpFormattingPolicy, TextStylePolicy textStylePolicy)
 {
     this.policy          = cSharpFormattingPolicy;
     this.textStylePolicy = textStylePolicy;
     FormatSample();
 }
 internal void SetPolicy(CSharpFormattingPolicy formattingPolicy, TextStylePolicy textStylePolicy)
 {
     policy = formattingPolicy;
     this.textStylePolicy = textStylePolicy;
     FormatSample();
 }
		public CSharpTextEditorCompletion ()
		{
			IEnumerable<string> types = MonoDevelop.Ide.DesktopService.GetMimeTypeInheritanceChain (CSharpFormatter.MimeType);
			policy = MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy<MonoDevelop.CSharp.Formatting.CSharpFormattingPolicy> (types);
		}
示例#14
0
        public static TooltipInformation CreateTooltipInformation(ICompilation compilation, CSharpUnresolvedFile file, TextEditorData textEditorData, MonoDevelop.CSharp.Formatting.CSharpFormattingPolicy formattingPolicy, IType type, bool smartWrap, bool createFooter = false)
        {
            var tooltipInfo = new TooltipInformation();
            var resolver    = file != null?file.GetResolver(compilation, textEditorData.Caret.Location) : new CSharpResolver(compilation);

            var sig = new SignatureMarkupCreator(resolver, formattingPolicy.CreateOptions());

            sig.BreakLineAfterReturnType = smartWrap;
            try {
                tooltipInfo.SignatureMarkup = sig.GetMarkup(type.IsParameterized ? type.GetDefinition() : type);
            } catch (Exception e) {
                LoggingService.LogError("Got exception while creating markup for :" + type, e);
                return(new TooltipInformation());
            }
            if (type.IsParameterized)
            {
                var typeInfo = new StringBuilder();
                for (int i = 0; i < type.TypeParameterCount; i++)
                {
                    typeInfo.AppendLine(type.GetDefinition().TypeParameters [i].Name + " is " + sig.GetTypeReferenceString(type.TypeArguments [i]));
                }
                tooltipInfo.AddCategory("Type Parameters", typeInfo.ToString());
            }

            var def = type.GetDefinition();

            if (def != null)
            {
                if (createFooter && !string.IsNullOrEmpty(def.ParentAssembly.AssemblyName))
                {
                    tooltipInfo.FooterMarkup = "<small> From " + AmbienceService.EscapeText(def.ParentAssembly.AssemblyName) + "</small>";
                }
                tooltipInfo.SummaryMarkup = AmbienceService.GetSummaryMarkup(def) ?? "";
            }
            return(tooltipInfo);
        }
示例#15
0
        public static TooltipInformation CreateTooltipInformation(ICompilation compilation, CSharpUnresolvedFile file, CSharpResolver resolver, TextEditorData textEditorData, MonoDevelop.CSharp.Formatting.CSharpFormattingPolicy formattingPolicy, IEntity entity, bool smartWrap, bool createFooter = false)
        {
            var tooltipInfo = new TooltipInformation();

            if (resolver == null)
            {
                resolver = file != null?file.GetResolver(compilation, textEditorData.Caret.Location) : new CSharpResolver(compilation);
            }
            var sig = new SignatureMarkupCreator(resolver, formattingPolicy.CreateOptions());

            sig.BreakLineAfterReturnType = smartWrap;
            try {
                tooltipInfo.SignatureMarkup = sig.GetMarkup(entity);
            } catch (Exception e) {
                LoggingService.LogError("Got exception while creating markup for :" + entity, e);
                return(new TooltipInformation());
            }
            tooltipInfo.SummaryMarkup = AmbienceService.GetSummaryMarkup(entity) ?? "";

            if (entity is IMember)
            {
                var evt = (IMember)entity;
                if (evt.ReturnType.Kind == TypeKind.Delegate)
                {
                    tooltipInfo.AddCategory(GettextCatalog.GetString("Delegate Info"), sig.GetDelegateInfo(evt.ReturnType));
                }
            }
            if (entity is IMethod)
            {
                var method = (IMethod)entity;
                if (method.IsExtensionMethod)
                {
                    tooltipInfo.AddCategory(GettextCatalog.GetString("Extension Method from"), method.DeclaringTypeDefinition.FullName);
                }
            }
            if (createFooter)
            {
                if (entity is IType)
                {
                    var type = entity as IType;
                    var def  = type.GetDefinition();
                    if (def != null)
                    {
                        if (!string.IsNullOrEmpty(def.ParentAssembly.AssemblyName))
                        {
                            var project = def.GetSourceProject();
                            if (project != null)
                            {
                                var relPath = FileService.AbsoluteToRelativePath(project.BaseDirectory, def.Region.FileName);
                                tooltipInfo.FooterMarkup = "<small>" + GettextCatalog.GetString("Project:\t{0}", AmbienceService.EscapeText(def.ParentAssembly.AssemblyName)) + "</small>" + Environment.NewLine +
                                                           "<small>" + GettextCatalog.GetString("File:\t\t{0} (line {1})", AmbienceService.EscapeText(relPath), def.Region.Begin.Line) + "</small>";
                            }
                        }
                    }
                }
                else if (entity.DeclaringTypeDefinition != null)
                {
                    var project = entity.DeclaringTypeDefinition.GetSourceProject();
                    if (project != null)
                    {
                        var relPath = FileService.AbsoluteToRelativePath(project.BaseDirectory, entity.Region.FileName);
                        tooltipInfo.FooterMarkup =
                            "<small>" + GettextCatalog.GetString("Project:\t{0}", AmbienceService.EscapeText(project.Name)) + "</small>" + Environment.NewLine +
                            "<small>" + GettextCatalog.GetString("From:\t{0}", AmbienceService.EscapeText(entity.DeclaringType.FullName)) + "</small>" + Environment.NewLine +
                            "<small>" + GettextCatalog.GetString("File:\t\t{0} (line {1})", AmbienceService.EscapeText(relPath), entity.Region.Begin.Line) + "</small>";
                    }
                }
            }
            return(tooltipInfo);
        }
示例#16
0
 public DomSpacingVisitor(CSharpFormattingPolicy policy, TextEditorData data)
 {
     this.policy       = policy;
     this.data         = data;
     AutoAcceptChanges = true;
 }
        public CSharpFormattingProfileDialog(CSharpFormattingPolicy profile)
        {
            // ReSharper disable once DoNotCallOverridableMethodsInConstructor
            this.Build();
            this.profile = profile;
            this.Title   = profile.IsBuiltIn ? GettextCatalog.GetString("Show built-in profile") : GettextCatalog.GetString("Edit Profile");

            notebookCategories.SwitchPage += delegate {
                TreeView treeView;
                switch (notebookCategories.Page)
                {
                case 0:
                    treeView = treeviewIndentOptions;
                    break;

                case 1:
                    treeView = treeviewNewLines;
                    break;

                case 2:                 // Blank lines
                    treeView = treeviewSpacing;
                    break;

                case 3:
                    treeView = treeviewWrapping;
                    break;

                default:
                    return;
                }

                TreeModel model;
                TreeIter  iter;
                if (treeView.Selection.GetSelected(out model, out iter))
                {
                    UpdateExample(model, iter);
                }
            };
            notebookCategories.ShowTabs = false;
            comboboxCategories.AppendText(GettextCatalog.GetString("Indentation"));
            comboboxCategories.AppendText(GettextCatalog.GetString("New Lines"));
            comboboxCategories.AppendText(GettextCatalog.GetString("Spacing"));
//			comboboxCategories.AppendText (GettextCatalog.GetString ("Style"));
            comboboxCategories.AppendText(GettextCatalog.GetString("Wrapping"));
            comboboxCategories.Changed += delegate {
                texteditor.Text         = "";
                notebookCategories.Page = comboboxCategories.Active;
            };
            comboboxCategories.Active = 0;

            var options = DefaultSourceEditorOptions.Instance;

            texteditor.Options    = DefaultSourceEditorOptions.PlainEditor;
            texteditor.IsReadOnly = true;
            texteditor.MimeType   = CSharpFormatter.MimeType;
            scrolledwindow.Child  = texteditor;
            ShowAll();

            #region Indent options
            indentationOptions = new TreeStore(typeof(string), typeof(string), typeof(string), typeof(bool), typeof(bool));

            var column = new TreeViewColumn();
            // pixbuf column
            var pixbufCellRenderer = new CellRendererImage();
            column.PackStart(pixbufCellRenderer, false);
            column.SetCellDataFunc(pixbufCellRenderer, RenderIcon);

            // text column
            var cellRendererText = new CellRendererText();
            cellRendererText.Ypad = 1;
            column.PackStart(cellRendererText, true);
            column.SetAttributes(cellRendererText, "text", 1);

            treeviewIndentOptions.Model              = indentationOptions;
            treeviewIndentOptions.HeadersVisible     = false;
            treeviewIndentOptions.Selection.Changed += TreeSelectionChanged;
            treeviewIndentOptions.AppendColumn(column);

            column = new TreeViewColumn();
            var cellRendererCombo = new CellRendererCombo();
            cellRendererCombo.Ypad       = 1;
            cellRendererCombo.Mode       = CellRendererMode.Editable;
            cellRendererCombo.TextColumn = 1;
            cellRendererCombo.Model      = ComboBoxStore;
            cellRendererCombo.HasEntry   = false;
            cellRendererCombo.Editable   = !profile.IsBuiltIn;

            cellRendererCombo.Edited += new ComboboxEditedHandler(this, indentationOptions).ComboboxEdited;

            column.PackStart(cellRendererCombo, false);
            column.SetAttributes(cellRendererCombo, "visible", comboVisibleColumn);
            column.SetCellDataFunc(cellRendererCombo, ComboboxDataFunc);

            var cellRendererToggle = new CellRendererToggle();
            cellRendererToggle.Ypad        = 1;
            cellRendererToggle.Activatable = !profile.IsBuiltIn;
            cellRendererToggle.Toggled    += new CellRendererToggledHandler(this, treeviewIndentOptions, indentationOptions).Toggled;
            column.PackStart(cellRendererToggle, false);
            column.SetAttributes(cellRendererToggle, "visible", toggleVisibleColumn);
            column.SetCellDataFunc(cellRendererToggle, ToggleDataFunc);
            treeviewIndentOptions.AppendColumn(column);


            AddOption(indentationOptions, "IndentBlock", GettextCatalog.GetString("Indent block contents"), "namespace Test { class AClass { void Method () { int x; int y; } } }");
            AddOption(indentationOptions, "IndentBraces", GettextCatalog.GetString("Indent open and close braces"), "class AClass { int aField; void AMethod () {}}");
            AddOption(indentationOptions, "IndentSwitchSection", GettextCatalog.GetString("Indent case contents"), "class AClass { void Method (int x) { switch (x) { case 1: break; } } }");
            AddOption(indentationOptions, "IndentSwitchCaseSection", GettextCatalog.GetString("Indent case labels"), "class AClass { void Method (int x) { switch (x) { case 1: break; } } }");
            AddOption(indentationOptions, "LabelPositioning", GettextCatalog.GetString("Label indentation"), "enum AEnum { A, B, C }");
            treeviewIndentOptions.ExpandAll();
            #endregion

            #region New line options
            newLineOptions = new TreeStore(typeof(string), typeof(string), typeof(string), typeof(bool), typeof(bool));

            column = new TreeViewColumn();
            // pixbuf column
            column.PackStart(pixbufCellRenderer, false);
            column.SetCellDataFunc(pixbufCellRenderer, RenderIcon);

            // text column
            cellRendererText      = new CellRendererText();
            cellRendererText.Ypad = 1;
            column.PackStart(cellRendererText, true);
            column.SetAttributes(cellRendererText, "text", 1);

            treeviewNewLines.Model              = newLineOptions;
            treeviewNewLines.HeadersVisible     = false;
            treeviewNewLines.Selection.Changed += TreeSelectionChanged;
            treeviewNewLines.AppendColumn(column);

            column                       = new TreeViewColumn();
            cellRendererCombo            = new CellRendererCombo();
            cellRendererCombo.Ypad       = 1;
            cellRendererCombo.Mode       = CellRendererMode.Editable;
            cellRendererCombo.TextColumn = 1;
            cellRendererCombo.Model      = ComboBoxStore;
            cellRendererCombo.HasEntry   = false;
            cellRendererCombo.Editable   = !profile.IsBuiltIn;
            cellRendererCombo.Edited    += new ComboboxEditedHandler(this, newLineOptions).ComboboxEdited;

            column.PackStart(cellRendererCombo, false);
            column.SetAttributes(cellRendererCombo, "visible", comboVisibleColumn);
            column.SetCellDataFunc(cellRendererCombo, ComboboxDataFunc);

            cellRendererToggle             = new CellRendererToggle();
            cellRendererToggle.Activatable = !profile.IsBuiltIn;
            cellRendererToggle.Ypad        = 1;
            cellRendererToggle.Toggled    += new CellRendererToggledHandler(this, treeviewNewLines, newLineOptions).Toggled;
            column.PackStart(cellRendererToggle, false);
            column.SetAttributes(cellRendererToggle, "visible", toggleVisibleColumn);
            column.SetCellDataFunc(cellRendererToggle, ToggleDataFunc);

            treeviewNewLines.AppendColumn(column);

            var category = AddOption(newLineOptions, null, GettextCatalog.GetString("New line options for braces"), null);
            AddOption(newLineOptions, category, "NewLinesForBracesInTypes", GettextCatalog.GetString("Place open brace on new line for types"), @"class Example
{
}");
            AddOption(newLineOptions, category, "NewLinesForBracesInMethods", GettextCatalog.GetString("Place open brace on new line for methods"), @"void Example()
{
}");
            AddOption(newLineOptions, category, "NewLinesForBracesInProperties", GettextCatalog.GetString("Place open brace on new line for properties"), @"int Example { 
	get  { 
		return 1;
	}
	set {
		// nothing
	}
}
"
                      );

            AddOption(newLineOptions, category, "NewLinesForBracesInAccessors", GettextCatalog.GetString("Place open brace on new line for property accessors"), @"int Example { 
	get  { 
		return 1;
	}
	set {
		// nothing
	}
}
"
                      );


            AddOption(newLineOptions, category, "NewLinesForBracesInAnonymousMethods", GettextCatalog.GetString("Place open brace on new line for anonymous methods"), @"void Example()
{
	var del = new delegate (int i, int j) {
	};
}");
            AddOption(newLineOptions, category, "NewLinesForBracesInControlBlocks", GettextCatalog.GetString("Place open brace on new line for control blocks"), @"void Example()
{
	if (true)
	{
	}
}");
            AddOption(newLineOptions, category, "NewLinesForBracesInAnonymousTypes", GettextCatalog.GetString("Place open brace on new line for anonymous types"), @"void Example()
{
	var c = new
	{
		A = 1,
		B = 2
	};
}");
            AddOption(newLineOptions, category, "NewLinesForBracesInObjectCollectionArrayInitializers", GettextCatalog.GetString("Place open brace on new line for object initializers"), @"void Example()
{
	new MyObject
	{
		A = 1,
		B = 2 
	};
}");
            AddOption(newLineOptions, category, "NewLinesForBracesInLambdaExpressionBody", GettextCatalog.GetString("Place open brace on new line for lambda expression"), @"void Example()
{
	Action act = () =>
	{
	};
}");

            category = AddOption(newLineOptions, null, GettextCatalog.GetString("New line options for keywords"), null);
            AddOption(newLineOptions, category, "NewLineForElse", GettextCatalog.GetString("Place \"else\" on new line"), @"void Example()
{
	if (true) {
		// ...
	} else {
		// ...
	}
}");
            AddOption(newLineOptions, category, "NewLineForCatch", GettextCatalog.GetString("Place \"catch\" on new line"), @"void Example()
{
	try {
	} catch {
	} finally {
	}
}");
            AddOption(newLineOptions, category, "NewLineForFinally", GettextCatalog.GetString("Place \"finally\" on new line"), @"void Example()
{
	try {
	} catch {
	} finally {
	}
}");

            category = AddOption(newLineOptions, null, GettextCatalog.GetString("New line options for expressions"), null);
            AddOption(newLineOptions, category, "NewLineForMembersInObjectInit", GettextCatalog.GetString("Place members in object initializers on new line"), @"void Example()
{
	new MyObject {
		A = 1,
		B = 2
	};
}");
            AddOption(newLineOptions, category, "NewLineForMembersInAnonymousTypes", GettextCatalog.GetString("Place members in anonymous types on new line"), @"void Example()
{
	var c = new
	{
		A = 1,
		B = 2
	};
}");
            AddOption(newLineOptions, category, "NewLineForClausesInQuery", GettextCatalog.GetString("Place query expression clauses on new line"), @"void Example()
{
	from o in col select o.Foo;
}");
            treeviewNewLines.ExpandAll();
            #endregion

            #region Spacing options
            spacingOptions = new TreeStore(typeof(string), typeof(string), typeof(string), typeof(bool), typeof(bool));

            column = new TreeViewColumn();
            // pixbuf column
            column.PackStart(pixbufCellRenderer, false);
            column.SetCellDataFunc(pixbufCellRenderer, RenderIcon);

            // text column
            cellRendererText.Ypad = 1;
            column.PackStart(cellRendererText, true);
            column.SetAttributes(cellRendererText, "text", 1);

            treeviewSpacing.Model              = spacingOptions;
            treeviewSpacing.HeadersVisible     = false;
            treeviewSpacing.Selection.Changed += TreeSelectionChanged;
            treeviewSpacing.AppendColumn(column);

            column                       = new TreeViewColumn();
            cellRendererCombo            = new CellRendererCombo();
            cellRendererCombo.Ypad       = 1;
            cellRendererCombo.Mode       = CellRendererMode.Editable;
            cellRendererCombo.TextColumn = 1;
            cellRendererCombo.Model      = ComboBoxStore;
            cellRendererCombo.HasEntry   = false;
            cellRendererCombo.Editable   = !profile.IsBuiltIn;
            cellRendererCombo.Edited    += new ComboboxEditedHandler(this, spacingOptions).ComboboxEdited;

            column.PackStart(cellRendererCombo, false);
            column.SetAttributes(cellRendererCombo, "visible", comboVisibleColumn);
            column.SetCellDataFunc(cellRendererCombo, ComboboxDataFunc);

            cellRendererToggle             = new CellRendererToggle();
            cellRendererToggle.Activatable = !profile.IsBuiltIn;
            cellRendererToggle.Ypad        = 1;
            cellRendererToggle.Toggled    += new CellRendererToggledHandler(this, treeviewSpacing, spacingOptions).Toggled;
            column.PackStart(cellRendererToggle, false);
            column.SetAttributes(cellRendererToggle, "visible", toggleVisibleColumn);
            column.SetCellDataFunc(cellRendererToggle, ToggleDataFunc);

            treeviewSpacing.AppendColumn(column);

            category = AddOption(spacingOptions, null, GettextCatalog.GetString("Set spacing for method declarations"), null);
            AddOption(spacingOptions, category, "SpacingAfterMethodDeclarationName", GettextCatalog.GetString("Insert space between method name and its opening parenthesis"),
                      @"void Example()
{
}");

            AddOption(spacingOptions, category, "SpaceWithinMethodDeclarationParenthesis", GettextCatalog.GetString("Insert space withing argument list parentheses"),
                      @"void Example(int i, int j)
{
}");
            AddOption(spacingOptions, category, "SpaceBetweenEmptyMethodDeclarationParentheses", GettextCatalog.GetString("Insert space within empty argument list parentheses"), @"void Example()
{
}");

            category = AddOption(spacingOptions, null, GettextCatalog.GetString("Set spacing for method calls"), null);
            AddOption(spacingOptions, category, "SpaceAfterMethodCallName", GettextCatalog.GetString("Insert space between method name and its opening parenthesis"), @"void Example()
{
	Test();
}");
            AddOption(spacingOptions, category, "SpaceWithinMethodCallParentheses", GettextCatalog.GetString("Insert space withing argument list parentheses"), @"void Example()
{
	Test(1, 2);
}");
            AddOption(spacingOptions, category, "SpaceBetweenEmptyMethodCallParentheses", GettextCatalog.GetString("Insert space within empty argument list parentheses"), @"void Example()
{
	Test();
}");

            category = AddOption(spacingOptions, null, GettextCatalog.GetString("Set other spacing options"), null);
            AddOption(spacingOptions, category, "SpaceAfterControlFlowStatementKeyword", GettextCatalog.GetString("Insert space after keywords in control flow statements"), @"void Example()
{
	if (condition)
	{
	}
}");

            AddOption(spacingOptions, category, "SpaceWithinExpressionParentheses", GettextCatalog.GetString("Insert space within parentheses of expressions"), @"void Example()
{
	i = (5 + 3) * 2;
}");
            AddOption(spacingOptions, category, "SpaceWithinCastParentheses", GettextCatalog.GetString("Insert space within parentheses of type casts"), @"void Example()
{
	test = (ITest)o;
}");
            AddOption(spacingOptions, category, "SpaceWithinOtherParentheses", GettextCatalog.GetString("Insert space within parentheses of control flow statements"), @"void Example()
{
	if (condition)
	{
	}
}");

            AddOption(spacingOptions, category, "SpaceAfterCast", GettextCatalog.GetString("Insert space after casts"), @"void Example()
{
	test = (ITest)o;
}");
            AddOption(spacingOptions, category, "SpacesIgnoreAroundVariableDeclaration", GettextCatalog.GetString("Ignore spaces in declaration statements"), @"void Example()
{
	int x=5;
}");

            category = AddOption(spacingOptions, null, GettextCatalog.GetString("Set spacing for brackets"), null);
            AddOption(spacingOptions, category, "SpaceBeforeOpenSquareBracket", GettextCatalog.GetString("Insert space before open square bracket"), @"void Example()
{
	i[5] = 3;
}");
            AddOption(spacingOptions, category, "SpaceBetweenEmptySquareBrackets", GettextCatalog.GetString("Insert space within empty square brackets"), @"void Example()
{
	new int[] {1, 2};
}");
            AddOption(spacingOptions, category, "SpaceWithinSquareBrackets", GettextCatalog.GetString("Insert space within square brackets"), @"void Example()
{
	i[5] = 3;
}");

            category = AddOption(spacingOptions, null, GettextCatalog.GetString("Set spacing for brackets"), null);
            AddOption(spacingOptions, category, "SpaceAfterColonInBaseTypeDeclaration", GettextCatalog.GetString("Insert space after colon for base or interface in type declaration"), @"class Foo : Bar
{
}");
            AddOption(spacingOptions, category, "SpaceAfterComma", GettextCatalog.GetString("Insert space after comma"), @"void Example()
{
	for (int i =0; i < 10, i >5;i++)
	{
	}
}");
            AddOption(spacingOptions, category, "SpaceAfterDot", GettextCatalog.GetString("Insert space after dot"), @"void Example()
{
	Foo.Bar.Test();
}");
            AddOption(spacingOptions, category, "SpaceAfterSemicolonsInForStatement", GettextCatalog.GetString("Insert space after semicolon in \"for\" statement"), @"void Example()
{
	for (int i = 0; i< 10; i++)
	{
	}
}");
            AddOption(spacingOptions, category, "SpaceBeforeColonInBaseTypeDeclaration", GettextCatalog.GetString("Insert space before colon for base or interface in type declaration"), @"class Foo : Bar
{
}");
            AddOption(spacingOptions, category, "SpaceBeforeComma", GettextCatalog.GetString("Insert space before comma"), @"void Example()
{
	for (int i =0; i < 10, i >5;i++)
	{
	}
}");
            AddOption(spacingOptions, category, "SpaceBeforeDot", GettextCatalog.GetString("Insert space before dot"), @"void Example()
{
	Foo.Bar.Test();
}");
            AddOption(spacingOptions, category, "SpaceBeforeSemicolonsInForStatement", GettextCatalog.GetString("Insert space before semicolon in \"for\" statement"), @"void Example()
{
	for (int i = 0; i< 10; i++)
	{
	}
}");

            AddOption(spacingOptions, category, "SpacingAroundBinaryOperator", GettextCatalog.GetString("Set spacing for operators"), @"void Example()
{
	i = (5 + 3) * 2;
}");

            treeviewSpacing.ExpandAll();
            #endregion

            #region Style options
            styleOptions = new TreeStore(typeof(string), typeof(string), typeof(string), typeof(bool), typeof(bool));

            column = new TreeViewColumn();
            // pixbuf column
            column.PackStart(pixbufCellRenderer, false);
            column.SetCellDataFunc(pixbufCellRenderer, RenderIcon);

            // text column
            cellRendererText.Ypad = 1;
            column.PackStart(cellRendererText, true);
            column.SetAttributes(cellRendererText, "text", 1);


            treeviewStyle.Model              = styleOptions;
            treeviewStyle.HeadersVisible     = false;
            treeviewStyle.Selection.Changed += TreeSelectionChanged;
            treeviewStyle.AppendColumn(column);

            column                       = new TreeViewColumn();
            cellRendererCombo            = new CellRendererCombo();
            cellRendererCombo.Ypad       = 1;
            cellRendererCombo.Mode       = CellRendererMode.Editable;
            cellRendererCombo.TextColumn = 1;
            cellRendererCombo.Model      = ComboBoxStore;
            cellRendererCombo.HasEntry   = false;
            cellRendererCombo.Editable   = !profile.IsBuiltIn;
            cellRendererCombo.Edited    += new ComboboxEditedHandler(this, styleOptions).ComboboxEdited;

            column.PackStart(cellRendererCombo, false);
            column.SetAttributes(cellRendererCombo, "visible", comboVisibleColumn);
            column.SetCellDataFunc(cellRendererCombo, ComboboxDataFunc);

            cellRendererToggle             = new CellRendererToggle();
            cellRendererToggle.Activatable = !profile.IsBuiltIn;
            cellRendererToggle.Ypad        = 1;
            cellRendererToggle.Toggled    += new CellRendererToggledHandler(this, treeviewSpacing, styleOptions).Toggled;
            column.PackStart(cellRendererToggle, false);
            column.SetAttributes(cellRendererToggle, "visible", toggleVisibleColumn);
            column.SetCellDataFunc(cellRendererToggle, ToggleDataFunc);

            treeviewStyle.AppendColumn(column);

            AddOption(styleOptions, category, null, GettextCatalog.GetString("Qualify member access with 'this'"), null);
            AddOption(styleOptions, category, null, GettextCatalog.GetString("Use 'var' when generating locals"), null);

            treeviewStyle.ExpandAll();
            #endregion

            #region Wrapping options
            wrappingOptions = new TreeStore(typeof(string), typeof(string), typeof(string), typeof(bool), typeof(bool));

            column = new TreeViewColumn();
            // pixbuf column
            column.PackStart(pixbufCellRenderer, false);
            column.SetCellDataFunc(pixbufCellRenderer, RenderIcon);

            // text column
            cellRendererText.Ypad = 1;
            column.PackStart(cellRendererText, true);
            column.SetAttributes(cellRendererText, "text", 1);

            treeviewWrapping.Model              = wrappingOptions;
            treeviewWrapping.HeadersVisible     = false;
            treeviewWrapping.Selection.Changed += TreeSelectionChanged;
            treeviewWrapping.AppendColumn(column);

            column                       = new TreeViewColumn();
            cellRendererCombo            = new CellRendererCombo();
            cellRendererCombo.Ypad       = 1;
            cellRendererCombo.Mode       = CellRendererMode.Editable;
            cellRendererCombo.TextColumn = 1;
            cellRendererCombo.Model      = ComboBoxStore;
            cellRendererCombo.HasEntry   = false;
            cellRendererCombo.Editable   = !profile.IsBuiltIn;
            cellRendererCombo.Edited    += new ComboboxEditedHandler(this, wrappingOptions).ComboboxEdited;

            column.PackStart(cellRendererCombo, false);
            column.SetAttributes(cellRendererCombo, "visible", comboVisibleColumn);
            column.SetCellDataFunc(cellRendererCombo, ComboboxDataFunc);

            cellRendererToggle             = new CellRendererToggle();
            cellRendererToggle.Activatable = !profile.IsBuiltIn;
            cellRendererToggle.Ypad        = 1;
            cellRendererToggle.Toggled    += new CellRendererToggledHandler(this, treeviewSpacing, wrappingOptions).Toggled;
            column.PackStart(cellRendererToggle, false);
            column.SetAttributes(cellRendererToggle, "visible", toggleVisibleColumn);
            column.SetCellDataFunc(cellRendererToggle, ToggleDataFunc);

            treeviewWrapping.AppendColumn(column);

            AddOption(wrappingOptions, "WrappingPreserveSingleLine", GettextCatalog.GetString("Leave block on single line"), "");
            AddOption(wrappingOptions, "WrappingKeepStatementsOnSingleLine", GettextCatalog.GetString("Leave statements and member declarations on the same line"), "");

            treeviewWrapping.ExpandAll();
            #endregion
        }
		public override void Initialize ()
		{
			base.Initialize ();
			dom = Document.Dom;
			textEditorData = Document.Editor;
			
			IEnumerable<string > types = MonoDevelop.Ide.DesktopService.GetMimeTypeInheritanceChain (CSharpFormatter.MimeType);
			if (dom != null && dom.Project != null)
				policy = dom.Project.Policies.Get<CSharpFormattingPolicy> (types);
			InitTracker ();
			UpdatePath (null, null);
			textEditorData.Caret.PositionChanged += UpdatePath;
			Document.DocumentParsed += HandleDocumentDocumentParsed;
		}
示例#19
0
        public static TooltipInformation CreateTooltipInformation(ICompilation compilation, CSharpUnresolvedFile file, CSharpResolver resolver, TextEditorData textEditorData, MonoDevelop.CSharp.Formatting.CSharpFormattingPolicy formattingPolicy, IEntity entity, bool smartWrap, bool createFooter = false)
        {
            var tooltipInfo = new TooltipInformation();

            if (resolver == null)
            {
                resolver = file != null?file.GetResolver(compilation, textEditorData.Caret.Location) : new CSharpResolver(compilation);
            }
            var sig = new SignatureMarkupCreator(resolver, formattingPolicy.CreateOptions());

            sig.BreakLineAfterReturnType = smartWrap;
            try {
                tooltipInfo.SignatureMarkup = sig.GetMarkup(entity);
            } catch (Exception e) {
                LoggingService.LogError("Got exception while creating markup for :" + entity, e);
                return(new TooltipInformation());
            }
            tooltipInfo.SummaryMarkup = AmbienceService.GetSummaryMarkup(entity) ?? "";

            if (entity is IMember)
            {
                var evt = (IMember)entity;
                if (evt.ReturnType.Kind == TypeKind.Delegate)
                {
                    tooltipInfo.AddCategory(GettextCatalog.GetString("Delegate Info"), sig.GetDelegateInfo(evt.ReturnType));
                }
            }
            if (entity is IMethod)
            {
                var method = (IMethod)entity;
                if (method.IsExtensionMethod)
                {
                    tooltipInfo.AddCategory(GettextCatalog.GetString("Extension Method from"), method.DeclaringTypeDefinition.FullName);
                }
            }
            if (createFooter)
            {
                tooltipInfo.FooterMarkup = sig.CreateFooter(entity);
            }
            return(tooltipInfo);
        }
示例#20
0
        public string FormatText(CSharpFormattingPolicy policy, TextStylePolicy textPolicy, string mimeType, string input, int startOffset, int endOffset)
        {
            var data = new TextEditorData();

            data.Document.SuppressHighlightUpdate = true;
            data.Document.MimeType = mimeType;
            data.Document.FileName = "toformat.cs";
            if (textPolicy != null)
            {
                data.Options.TabsToSpaces     = textPolicy.TabsToSpaces;
                data.Options.TabSize          = textPolicy.TabWidth;
                data.Options.DefaultEolMarker = textPolicy.GetEolMarker();
            }
            data.Options.OverrideDocumentEolMarker = true;
            data.Text = input;

//			System.Console.WriteLine ("-----");
//			System.Console.WriteLine (data.Text.Replace (" ", ".").Replace ("\t", "->"));
//			System.Console.WriteLine ("-----");

            var  parser          = new CSharpParser();
            var  compilationUnit = parser.Parse(data);
            bool hadErrors       = parser.HasErrors;

            if (hadErrors)
            {
//				foreach (var e in parser.ErrorReportPrinter.Errors)
//					Console.WriteLine (e.Message);
                return(input.Substring(startOffset, Math.Max(0, Math.Min(endOffset, input.Length) - startOffset)));
            }
            var adapter           = new TextEditorDataAdapter(data);
            var formattingVisitor = new ICSharpCode.NRefactory.CSharp.AstFormattingVisitor(policy.CreateOptions(), adapter, new FormattingActionFactory(data))
            {
                HadErrors = hadErrors
            };

            compilationUnit.AcceptVisitor(formattingVisitor, null);


            var changes = new List <ICSharpCode.NRefactory.CSharp.Refactoring.Action> ();

            changes.AddRange(formattingVisitor.Changes.
                             Where(c => (startOffset <= c.Offset && c.Offset < endOffset)));

            MDRefactoringContext.MdScript.RunActions(changes, null);

            // check if the formatter has produced errors
            parser = new CSharpParser();
            parser.Parse(data);
            if (parser.HasErrors)
            {
                LoggingService.LogError("C# formatter produced source code errors. See console for output.");
                Console.WriteLine(data.Text);
                return(input.Substring(startOffset, Math.Max(0, Math.Min(endOffset, input.Length) - startOffset)));
            }

            int end = endOffset;

            foreach (TextReplaceAction c in changes)
            {
                end -= c.RemovedChars;
                if (c.InsertedText != null)
                {
                    end += c.InsertedText.Length;
                }
            }

            /*			System.Console.WriteLine ("-----");
             *      System.Console.WriteLine (data.Text.Replace (" ", "^").Replace ("\t", "->"));
             *      System.Console.WriteLine ("-----");*/
            string result = data.GetTextBetween(startOffset, Math.Min(data.Length, end));

            data.Dispose();
            return(result);
        }
示例#21
0
 public static TooltipInformation CreateTooltipInformation(ICompilation compilation, CSharpUnresolvedFile file, TextEditorData textEditorData, MonoDevelop.CSharp.Formatting.CSharpFormattingPolicy formattingPolicy, IEntity entity, bool smartWrap, bool createFooter = false)
 {
     return(CreateTooltipInformation(compilation, file, null, textEditorData, formattingPolicy, entity, smartWrap, createFooter));
 }