public OverrideEqualsGetHashCodeMethodsDialog(InsertionContext context, ITextEditor editor, ITextAnchor startAnchor, ITextAnchor endAnchor,
		                                              ITextAnchor insertionPosition, IClass selectedClass, IMethod selectedMethod, string baseCall)
			: base(context, editor, insertionPosition)
		{
			if (selectedClass == null)
				throw new ArgumentNullException("selectedClass");
			
			InitializeComponent();
			
			this.selectedClass = selectedClass;
			this.startAnchor = startAnchor;
			this.insertionEndAnchor = endAnchor;
			this.selectedMethod = selectedMethod;
			this.baseCall = baseCall;
			
			addIEquatable.Content = string.Format(StringParser.Parse("${res:AddIns.SharpRefactoring.OverrideEqualsGetHashCodeMethods.AddInterface}"),
			                                      "IEquatable<" + selectedClass.Name + ">");
			
			string otherMethod = selectedMethod.Name == "Equals" ? "GetHashCode" : "Equals";
			
			addOtherMethod.Content = StringParser.Parse("${res:AddIns.SharpRefactoring.OverrideEqualsGetHashCodeMethods.AddOtherMethod}", new StringTagPair("otherMethod", otherMethod));
			
			addIEquatable.IsEnabled = !selectedClass.BaseTypes.Any(
				type => {
					if (!type.IsGenericReturnType)
						return false;
					var genericType = type.CastToGenericReturnType();
					var boundTo = genericType.TypeParameter.BoundTo;
					if (boundTo == null)
						return false;
					return boundTo.Name == selectedClass.Name;
				}
			);
		}
		protected void OpenAtPosition(ITextEditor editor, int line, int column, bool openAtWordStart)
		{
			var editorUIService = editor == null ? null : editor.GetService(typeof(IEditorUIService)) as IEditorUIService;
			if (editorUIService != null) {
				var document = editor.Document;
				int offset = document.PositionToOffset(line, column);
				if (openAtWordStart) {
					int wordStart = document.FindPrevWordStart(offset);
					if (wordStart != -1) {
						var wordStartLocation = document.OffsetToPosition(wordStart);
						line = wordStartLocation.Line;
						column = wordStartLocation.Column;
					}
				}
				this.Placement = PlacementMode.Absolute;
				try
				{
					var caretScreenPos = editorUIService.GetScreenPosition(line, column);
					this.HorizontalOffset = caretScreenPos.X;
					this.VerticalOffset = caretScreenPos.Y;
				}
				catch
				{
					this.Placement = PlacementMode.MousePoint;
				}
				
			} else {
				// if no editor information, open at mouse positions
				this.Placement = PlacementMode.MousePoint;
			}
			this.Open();
		}
		public override void IndentLines(ITextEditor editor, int beginLine, int endLine)
		{
			DocumentAccessor acc = new DocumentAccessor(editor.Document, beginLine, endLine);
			CSharpIndentationStrategy indentStrategy = new CSharpIndentationStrategy();
			indentStrategy.IndentationString = editor.Options.IndentationString;
			indentStrategy.Indent(acc, true);
		}
Beispiel #4
0
		protected override void RunImpl(ITextEditor editor, int offset, ResolveResult symbol)
		{
			if (symbol == null)
				return;
			
			FilePosition pos = symbol.GetDefinitionPosition();
			if (pos.IsEmpty) {
				IEntity entity;
				if (symbol is MemberResolveResult) {
					entity = ((MemberResolveResult)symbol).ResolvedMember;
				} else if (symbol is TypeResolveResult) {
					entity = ((TypeResolveResult)symbol).ResolvedClass;
				} else {
					entity = null;
				}
				if (entity != null) {
					NavigationService.NavigateTo(entity);
				}
			} else {
				try {
					if (pos.Position.IsEmpty)
						FileService.OpenFile(pos.FileName);
					else
						FileService.JumpToFilePosition(pos.FileName, pos.Line, pos.Column);
				} catch (Exception ex) {
					MessageService.ShowException(ex, "Error jumping to '" + pos.FileName + "'.");
				}
			}
		}
		public SharpDevelopCompletionWindow(ITextEditor editor, TextArea textArea, ICompletionItemList itemList) : base(textArea)
		{
			if (editor == null)
				throw new ArgumentNullException("editor");
			if (itemList == null)
				throw new ArgumentNullException("itemList");
			
			if (!itemList.ContainsAllAvailableItems) {
				// If more items are available (Ctrl+Space wasn't pressed), show this hint
				this.EmptyText = StringParser.Parse("${res:ICSharpCode.AvalonEdit.AddIn.SharpDevelopCompletionWindow.EmptyText}");
			}
			
			InitializeComponent();
			this.Editor = editor;
			this.itemList = itemList;
			ICompletionItem suggestedItem = itemList.SuggestedItem;
			foreach (ICompletionItem item in itemList.Items) {
				ICompletionData adapter = new CodeCompletionDataAdapter(this, item);
				this.CompletionList.CompletionData.Add(adapter);
				if (item == suggestedItem)
					this.CompletionList.SelectedItem = adapter;
			}
			this.StartOffset -= itemList.PreselectionLength;
			this.EndOffset += itemList.PostselectionLength;
		}
		protected bool ProvideContextCompletion(ITextEditor editor, IReturnType expected, char charTyped)
		{
			if (expected == null) return false;
			IClass c = expected.GetUnderlyingClass();
			if (c == null) return false;
			if (c.ClassType == ClassType.Enum) {
				CtrlSpaceCompletionItemProvider cdp = new NRefactoryCtrlSpaceCompletionItemProvider(languageProperties);
				var ctrlSpaceList = cdp.GenerateCompletionList(editor);
				if (ctrlSpaceList == null) return false;
				ContextCompletionItemList contextList = new ContextCompletionItemList();
				contextList.Items.AddRange(ctrlSpaceList.Items);
				contextList.activationKey = charTyped;
				foreach (CodeCompletionItem item in contextList.Items.OfType<CodeCompletionItem>()) {
					IClass itemClass = item.Entity as IClass;
					if (itemClass != null && c.FullyQualifiedName == itemClass.FullyQualifiedName && c.TypeParameters.Count == itemClass.TypeParameters.Count) {
						contextList.SuggestedItem = item;
						break;
					}
				}
				if (contextList.SuggestedItem != null) {
					if (charTyped != ' ') contextList.InsertSpace = true;
					editor.ShowCompletionWindow(contextList);
					return true;
				}
			}
			return false;
		}
		public EditorScript(ITextEditor editor, SDRefactoringContext context, CSharpFormattingOptions formattingOptions)
			: base(editor.Document, formattingOptions, context.TextEditorOptions)
		{
			this.editor = editor;
			this.context = context;
			this.textSegmentCollection = new TextSegmentCollection<TextSegment>((TextDocument)editor.Document);
		}
		public void Attach(ITextEditor editor)
		{
			this.editor = editor;
			inspectionManager = new IssueManager(editor);
			codeManipulation = new CodeManipulation(editor);
			renderer = new CaretReferenceHighlightRenderer(editor);
			
			// Patch editor options (indentation) to project-specific settings
			if (!editor.ContextActionProviders.IsReadOnly) {
				contextActionProviders = AddInTree.BuildItems<IContextActionProvider>("/SharpDevelop/ViewContent/TextEditor/C#/ContextActions", null);
				editor.ContextActionProviders.AddRange(contextActionProviders);
			}
			
			// Create instance of options adapter and register it as service
			var formattingPolicy = CSharpFormattingPolicies.Instance.GetProjectOptions(
				SD.ProjectService.FindProjectContainingFile(editor.FileName));
			options = new CodeEditorFormattingOptionsAdapter(editor.Options, formattingPolicy.OptionsContainer);
			var textEditor = editor.GetService<TextEditor>();
			if (textEditor != null) {
				var textViewServices = textEditor.TextArea.TextView.Services;
				
				// Unregister any previous ITextEditorOptions instance from editor, if existing, register our impl.
				textViewServices.RemoveService(typeof(ITextEditorOptions));
				textViewServices.AddService(typeof(ITextEditorOptions), options);
				
				// Set TextEditor's options to same object
				originalEditorOptions = textEditor.Options;
				textEditor.Options = options;
			}
		}
		public OverrideEqualsGetHashCodeMethodsDialog(InsertionContext context, ITextEditor editor, ITextAnchor endAnchor,
		                                              ITextAnchor insertionPosition, ITypeDefinition selectedClass, IMethod selectedMethod, AstNode baseCallNode)
			: base(context, editor, insertionPosition)
		{
			if (selectedClass == null)
				throw new ArgumentNullException("selectedClass");
			
			InitializeComponent();
			
			this.selectedClass = selectedClass;
			this.insertionEndAnchor = endAnchor;
			this.selectedMethod = selectedMethod;
			this.baseCallNode = baseCallNode;
			
			addIEquatable.Content = string.Format(StringParser.Parse("${res:AddIns.SharpRefactoring.OverrideEqualsGetHashCodeMethods.AddInterface}"),
			                                      "IEquatable<" + selectedClass.Name + ">");
			
			string otherMethod = selectedMethod.Name == "Equals" ? "GetHashCode" : "Equals";
			
			addOtherMethod.Content = StringParser.Parse("${res:AddIns.SharpRefactoring.OverrideEqualsGetHashCodeMethods.AddOtherMethod}", new StringTagPair("otherMethod", otherMethod));
			
			addIEquatable.IsEnabled = !selectedClass.GetAllBaseTypes().Any(
				type => {
					if (!type.IsParameterized || (type.TypeParameterCount != 1))
						return false;
					if (type.FullName != "System.IEquatable")
						return false;
					return type.TypeArguments.First().FullName == selectedClass.FullName;
				}
			);
		}
		public ToolTipRequestEventArgs(ITextEditor editor)
		{
			if (editor == null)
				throw new ArgumentNullException("editor");
			this.Editor = editor;
			this.InDocument = true;
		}
		public override void Attach(ITextEditor editor)
		{
			base.Attach(editor);
			
			// try to access the ICSharpCode.AvalonEdit.Rendering.TextView
			// of this ITextEditor
			this.textView = editor.GetService(typeof(TextView)) as TextView;
			
			// if editor is not an AvalonEdit.TextEditor
			// GetService returns null
			if (textView != null) {
				if (SD.Workbench != null) {
//					if (XamlBindingOptions.UseAdvancedHighlighting) {
//						colorizer = new XamlColorizer(editor, textView);
//						// attach the colorizer
//						textView.LineTransformers.Add(colorizer);
//					}
					// add the XamlOutlineContentHost, which manages the tree view
					contentHost = new XamlOutlineContentHost(editor);
					textView.Services.AddService(typeof(IOutlineContentHost), contentHost);
				}
				// add ILanguageBinding
				textView.Services.AddService(typeof(XamlTextEditorExtension), this);
			}
			
			SD.ParserService.ParseInformationUpdated += ParseInformationUpdated;
		}
		public ICSharpCodeCoreTagCompletionItemList(ITextEditor editor)
			: base()
		{
			var item = new DefaultCompletionItem("{res") { Image = ClassBrowserIconService.Keyword };
			this.Items.Add(item);
			this.SuggestedItem = item;
		}
		protected override bool Refactor(ITextEditor editor, XDocument document)
		{
			if (editor.SelectionLength == 0) {
				MessageService.ShowError("Nothing selected!");
				return false;
			}
			
			Location startLoc = editor.Document.OffsetToPosition(editor.SelectionStart);
			Location endLoc = editor.Document.OffsetToPosition(editor.SelectionStart + editor.SelectionLength);
			
			var selectedItems = (from item in document.Root.Descendants()
			                     where item.IsInRange(startLoc, endLoc) select item).ToList();
			
			if (selectedItems.Any()) {
				var parent = selectedItems.First().Parent;
				
				currentWpfNamespace = parent.GetCurrentNamespaces()
					.First(i => CompletionDataHelper.WpfXamlNamespaces.Contains(i));
				
				var items = selectedItems.Where(i => i.Parent == parent);
				
				return GroupInto(parent, items);
			}
			
			return false;
		}
		/// <inheritdoc/>
		public override ICompletionItemList GenerateCompletionList(ITextEditor editor)
		{
			if (editor == null)
				throw new ArgumentNullException("textEditor");
			ExpressionResult expression = GetExpression(editor);
			return GenerateCompletionListForExpression(editor, expression);
		}
		public override void IndentLine(ITextEditor editor, IDocumentLine line)
		{
			LineIndenter indenter = CreateLineIndenter(editor, line);
			if (!indenter.Indent()) {
				base.IndentLine(editor, line);
			}
		}
		public void InitializeOpenedInsightWindow(ITextEditor editor, IInsightWindow insightWindow)
		{
			EventHandler<TextChangeEventArgs> onDocumentChanged = delegate {
				// whenever the document is changed, recalculate EndOffset
				var remainingDocument = editor.Document.CreateReader(insightWindow.StartOffset, editor.Document.TextLength - insightWindow.StartOffset);
				using (ILexer lexer = ParserFactory.CreateLexer(language, remainingDocument)) {
					lexer.SetInitialLocation(editor.Document.OffsetToPosition(insightWindow.StartOffset));
					Token token;
					int bracketCount = 0;
					while ((token = lexer.NextToken()) != null && token.Kind != eofToken) {
						if (token.Kind == openParensToken || token.Kind == openBracketToken || token.Kind == openBracketToken) {
							bracketCount++;
						} else if (token.Kind == closeParensToken || token.Kind == closeBracketToken || token.Kind == closeBracesToken) {
							bracketCount--;
							if (bracketCount <= 0) {
								MarkInsightWindowEndOffset(insightWindow, editor, token.Location);
								break;
							}
						} else if (token.Kind == statementEndToken) {
							MarkInsightWindowEndOffset(insightWindow, editor, token.Location);
							break;
						}
					}
				}
			};
			insightWindow.DocumentChanged += onDocumentChanged;
			insightWindow.SelectedItemChanged += delegate { HighlightParameter(insightWindow, highlightedParameter); };
			onDocumentChanged(null, null);
		}
 public FoldingManagerAdapter(ITextEditor textEditor)
 {
     AvalonEditTextEditorAdapter adaptor = textEditor as AvalonEditTextEditorAdapter;
     if (adaptor != null) {
         this.foldingManager = FoldingManager.Install(adaptor.TextEditor.TextArea);
     }
 }
		public void CreatePins(ITextEditor editor)
		{
			// load pins
			var pins = BookmarkManager.Bookmarks.FindAll(
				b => b is PinBookmark && b.FileName == editor.FileName);
			
			foreach (var bookmark in pins) {
				var pin = (PinBookmark)bookmark;
				pin.Popup = new PinDebuggerControl();
				pin.Popup.Mark = pin;
				
				var nodes = new ObservableCollection<ITreeNode>();
				foreach (var tuple in pin.SavedNodes) {
					string imageName = !string.IsNullOrEmpty(tuple.Item1) ? tuple.Item1 : "Icons.16x16.Field";
					var node = new Debugger.AddIn.TreeModel.SavedTreeNode(
						new ResourceServiceImage(imageName),
						tuple.Item2,
						tuple.Item3);
					node.ImageName = imageName;
					nodes.Add(node);
				}
				
				pin.SavedNodes.Clear();
				pin.Popup.ItemsSource = nodes;
				pin.Nodes = nodes;
				
				pinLayer.Pin((PinDebuggerControl)pin.Popup);
			}
		}
		public void ClosePins(ITextEditor editor)
		{
			// save pins
			var pins = BookmarkManager.Bookmarks.FindAll(
				b => b is PinBookmark && b.FileName == editor.FileName);
			
			foreach (var bookmark in pins) {
				var pin = (PinBookmark)bookmark;
				if (!pin.PinPosition.HasValue)
					pin.PinPosition = pin.Popup.Location;
				
				// nodes
				if (pin.SavedNodes == null)
					pin.SavedNodes = new System.Collections.Generic.List<Tuple<string, string, string>>();
				
				foreach (var node in pin.Nodes) {
					pin.SavedNodes.Add(
						new Tuple<string, string, string>(
							"Icons.16x16.Field",
							node.FullName,
							node.Text));
				}
				
				pinLayer.Unpin((PinDebuggerControl)pin.Popup);
				pin.Popup = null;
			}
		}
Beispiel #20
0
		public IInsightItem[] ProvideInsight(ITextEditor editor)
		{
			if (editor == null)
				throw new ArgumentNullException("editor");
			
			IExpressionFinder expressionFinder = ParserService.GetExpressionFinder(editor.FileName);
			if (expressionFinder == null) {
				return null;
			}
			
			IDocument document = editor.Document;
			int useOffset = (this.LookupOffset < 0) ? editor.Caret.Offset : this.LookupOffset;
			ExpressionResult expressionResult = expressionFinder.FindExpression(document.Text, useOffset);
			
			if (expressionResult.Expression == null) // expression is null when cursor is in string/comment
				return null;
			
			if (LoggingService.IsDebugEnabled) {
				if (expressionResult.Context == ExpressionContext.Default)
					LoggingService.DebugFormatted("ShowInsight for >>{0}<<", expressionResult.Expression);
				else
					LoggingService.DebugFormatted("ShowInsight for >>{0}<<, context={1}", expressionResult.Expression, expressionResult.Context);
			}
			
			var position = document.OffsetToPosition(useOffset);
			ResolveResult rr = ParserService.Resolve(expressionResult, position.Line, position.Column, editor.FileName, document.Text);
			return ProvideInsight(expressionResult, rr);
		}
        void ITextEditorExtension.Attach(ITextEditor editor)
        {
            _outlineContent = new ModuleOutlineControl(editor);

            _textView = editor.GetService(typeof(TextView)) as TextView;
            _textView.Services.AddService(typeof(IOutlineContentHost), _outlineContent);
        }
		public SendToScriptingConsoleCommand(IScriptingWorkbench workbench)
		{
			this.workbench = workbench;
			
			textEditorView = new ScriptingTextEditorViewContent(workbench);
			activeTextEditor = textEditorView.TextEditor;
		}
        internal ModuleOutlineControl(ITextEditor textEditor)
            : this()
        {
            _textEditor = textEditor;

            SD.ParserService.ParseInformationUpdated += ParserService_ParseInformationUpdated;
        }
		protected override bool Refactor(ITextEditor editor, XDocument document)
		{
			Location startLoc = editor.Document.OffsetToPosition(editor.SelectionStart);
			Location endLoc = editor.Document.OffsetToPosition(editor.SelectionStart + editor.SelectionLength);
			
			XName[] names = CompletionDataHelper.WpfXamlNamespaces.Select(item => XName.Get("Grid", item)).ToArray();
			
			XElement selectedItem = document.Root.Descendants()
				.FirstOrDefault(item => item.IsInRange(startLoc, endLoc) && names.Any(ns => ns == item.Name))
				?? document.Root.Elements().FirstOrDefault(i => names.Any(ns => ns == i.Name));
			
			if (selectedItem == null) {
				MessageService.ShowError("Please select a Grid!");
				return false;
			}
			
			EditGridColumnsAndRowsDialog dialog = new EditGridColumnsAndRowsDialog(selectedItem);
			dialog.Owner = WorkbenchSingleton.MainWindow;
			
			if (dialog.ShowDialog() == true) {
				selectedItem.ReplaceWith(dialog.ConstructedTree);
				return true;
			}
			
			return false;
		}
        public CodeCompletionKeyPressResult HandleKeyPress(ITextEditor editor, char ch)
        {
            if (this.CompletionPossible(editor, ch)) {

                ResourceResolveResult result = ResourceResolverService.Resolve(editor, ch);
                if (result != null) {
                    IResourceFileContent content;
                    if ((content = result.ResourceFileContent) != null) {

                        // If the resolved resource set is the local ICSharpCode.Core resource set
                        // (this may happen through the ICSharpCodeCoreNRefactoryResourceResolver),
                        // we will have to merge in the host resource set (if available)
                        // for the code completion window.
                        if (result.ResourceSetReference.ResourceSetName == ICSharpCodeCoreResourceResolver.ICSharpCodeCoreLocalResourceSetName) {
                            IResourceFileContent hostContent = ICSharpCodeCoreResourceResolver.GetICSharpCodeCoreHostResourceSet(editor.FileName).ResourceFileContent;
                            if (hostContent != null) {
                                content = new MergedResourceFileContent(content, new IResourceFileContent[] { hostContent });
                            }
                        }

                        editor.ShowCompletionWindow(new ResourceCodeCompletionItemList(content, this.OutputVisitor, result.CallingClass != null ? result.CallingClass.Name+"." : null));
                        return CodeCompletionKeyPressResult.Completed;
                    }
                }

            }

            return CodeCompletionKeyPressResult.None;
        }
		/// <summary>
		/// Default implementation for single line comments.
		/// </summary>
		protected void SurroundSelectionWithSingleLineComment(ITextEditor editor, string comment)
		{
			IDocument document = editor.Document;
			using (document.OpenUndoGroup()) {
				TextLocation startPosition = document.GetLocation(editor.SelectionStart);
				TextLocation endPosition = document.GetLocation(editor.SelectionStart + editor.SelectionLength);
				
				// endLine is one above endPosition if no characters are selected on the last line (e.g. line selection from the margin)
				int endLine = (endPosition.Column == 1 && endPosition.Line > startPosition.Line) ? endPosition.Line - 1 : endPosition.Line;
				
				List<IDocumentLine> lines = new List<IDocumentLine>();
				bool removeComment = true;
				
				for (int i = startPosition.Line; i <= endLine; i++) {
					lines.Add(editor.Document.GetLineByNumber(i));
					if (!document.GetText(lines[i - startPosition.Line]).Trim().StartsWith(comment, StringComparison.Ordinal))
						removeComment = false;
				}
				
				foreach (IDocumentLine line in lines) {
					if (removeComment) {
						document.Remove(line.Offset + document.GetText(line).IndexOf(comment, StringComparison.Ordinal), comment.Length);
					} else {
						document.Insert(line.Offset, comment, AnchorMovementType.BeforeInsertion);
					}
				}
			}
		}
 public override void IndentLines(ITextEditor editor, int beginLine, int endLine)
 {
     //DocumentAccessor acc = new DocumentAccessor(editor.Document, beginLine, endLine);
     //CSharpIndentationStrategy indentStrategy = new CSharpIndentationStrategy();
     //indentStrategy.IndentationString = editor.Options.IndentationString;
     //indentStrategy.Indent(acc, true);
     SharpLua.Visitors.NonModifiedAstBeautifier b = null;
     try
     {
         Lexer l = new Lexer();
         Parser p = new Parser(l.Lex(editor.Document.Text));
         SharpLua.Ast.Chunk c = p.Parse();
         b = new SharpLua.Visitors.NonModifiedAstBeautifier();
         //SharpLua.Visitors.ExactReconstruction b = new SharpLua.Visitors.ExactReconstruction();
         b.options.Tab = editor.Options.IndentationString;
         b.options.TabsToSpaces = editor.Options.ConvertTabsToSpaces;
         int off = editor.Caret.Offset;
         //editor.Document.Text = b.Reconstruct(c);
         editor.Document.Text = b.Beautify(c);
         editor.Caret.Offset = off >= editor.Document.TextLength ? 0 : off;
     }
     catch (LuaSourceException ex)
     {
         LoggingService.Warn("Error parsing document: " + System.IO.Path.GetFileName(ex.GenerateMessage(editor.FileName)));
     }
     catch (System.Exception ex)
     {
         LoggingService.Error("Error formatting document:", ex);
         MessageBox.Show(b.index.ToString() + " "+ b.tok.Count);
         MessageBox.Show("Error formatting Lua script: " + ex.ToString() + "\r\n\r\nPlease report this to the SharpLua GitHub page so it can get fixed");
     }
 }
Beispiel #28
0
		/// <summary>
		/// Formats the specified part of the document.
		/// </summary>
		public static void Format(ITextEditor editor, int offset, int length, CSharpFormattingOptions options)
		{
			var formatter = new CSharpFormatter(options, editor.ToEditorOptions());
			formatter.AddFormattingRegion(new DomRegion(editor.Document.GetLocation(offset), editor.Document.GetLocation(offset + length)));
			var changes = formatter.AnalyzeFormatting(editor.Document, SyntaxTree.Parse(editor.Document));
			changes.ApplyChanges(offset, length);
		}
		public AutoCompleteTextBox()
		{
			object tmp;
			this.editorAdapter = SD.EditorControlService.CreateEditor(out tmp);
			this.editor = (TextEditor)tmp;
			
			this.editor.Background = Brushes.Transparent;
			this.editor.ClearValue(TextEditor.FontFamilyProperty);
			this.editor.ClearValue(TextEditor.FontSizeProperty);
			this.editor.ShowLineNumbers = false;
			this.editor.WordWrap = false;
			this.editor.HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden;
			this.editor.VerticalScrollBarVisibility = ScrollBarVisibility.Hidden;
			this.editor.TextArea.GotKeyboardFocus += delegate {
				this.Background = Brushes.White;
				this.Foreground = Brushes.Black;
			};
			this.editor.TextArea.LostKeyboardFocus += delegate {
				this.Background = Brushes.Transparent;
				this.ClearValue(ForegroundProperty);
				this.Text = this.editor.Text;
				this.editorAdapter.ClearSelection();
			};
			this.editor.TextArea.PreviewKeyDown += editor_TextArea_PreviewKeyDown;
			this.editor.TextArea.TextEntered += editor_TextArea_TextEntered;
			
			this.Content = this.editor.TextArea;
			
			HorizontalContentAlignment = HorizontalAlignment.Stretch;
			VerticalContentAlignment = VerticalAlignment.Stretch;
		}
		protected override void Run(ITextEditor editor, IBookmarkMargin bookmarkMargin)
		{
			int lineNumber = editor.Caret.Line;
			if (!SD.BookmarkManager.RemoveBookmarkAt(editor.FileName, lineNumber, b => b is Bookmark)) {
				SD.BookmarkManager.AddMark(new Bookmark(), editor.Document, lineNumber);
			}
		}
 public static IEnumerable <AddUsingAction> GetAddUsingActions(UnknownConstructorCallResolveResult rr, ITextEditor textArea)
 {
     return(GetAddUsingActionsForUnknownClass(rr.CallingClass, rr.TypeName, textArea));
 }
Beispiel #32
0
 public virtual void FormatLine(ITextEditor editor, char charTyped)
 {
 }
Beispiel #33
0
        public static BlockCommentRegion FindSelectedCommentRegion(ITextEditor editor, string commentStart, string commentEnd)
        {
            IDocument document = editor.Document;

            if (document.TextLength == 0)
            {
                return(null);
            }

            // Find start of comment in selected text.

            int    commentEndOffset = -1;
            string selectedText     = editor.SelectedText;

            int commentStartOffset = selectedText.IndexOf(commentStart);

            if (commentStartOffset >= 0)
            {
                commentStartOffset += editor.SelectionStart;
            }

            // Find end of comment in selected text.

            if (commentStartOffset >= 0)
            {
                commentEndOffset = selectedText.IndexOf(commentEnd, commentStartOffset + commentStart.Length - editor.SelectionStart);
            }
            else
            {
                commentEndOffset = selectedText.IndexOf(commentEnd);
            }

            if (commentEndOffset >= 0)
            {
                commentEndOffset += editor.SelectionStart;
            }

            // Find start of comment before or partially inside the
            // selected text.

            int commentEndBeforeStartOffset = -1;

            if (commentStartOffset == -1)
            {
                int offset = editor.SelectionStart + editor.SelectionLength + commentStart.Length - 1;
                if (offset > document.TextLength)
                {
                    offset = document.TextLength;
                }
                string text = document.GetText(0, offset);
                commentStartOffset = text.LastIndexOf(commentStart);
                if (commentStartOffset >= 0)
                {
                    // Find end of comment before comment start.
                    commentEndBeforeStartOffset = text.IndexOf(commentEnd, commentStartOffset, editor.SelectionStart - commentStartOffset);
                    if (commentEndBeforeStartOffset > commentStartOffset)
                    {
                        commentStartOffset = -1;
                    }
                }
            }

            // Find end of comment after or partially after the
            // selected text.

            if (commentEndOffset == -1)
            {
                int offset = editor.SelectionStart + 1 - commentEnd.Length;
                if (offset < 0)
                {
                    offset = editor.SelectionStart;
                }
                string text = document.GetText(offset, document.TextLength - offset);
                commentEndOffset = text.IndexOf(commentEnd);
                if (commentEndOffset >= 0)
                {
                    commentEndOffset += offset;
                }
            }

            if (commentStartOffset != -1 && commentEndOffset != -1)
            {
                return(new BlockCommentRegion(commentStart, commentEnd, commentStartOffset, commentEndOffset));
            }

            return(null);
        }
 public virtual bool CtrlSpace(ITextEditor editor)
 {
     return(false);
 }
 public virtual bool HandleKeyword(ITextEditor editor, string word)
 {
     // DefaultCodeCompletionBinding does not support Keyword handling, but this
     // method can be overridden
     return(false);
 }
        public virtual CodeCompletionKeyPressResult HandleKeyPress(ITextEditor editor, char ch)
        {
            switch (ch)
            {
            case '(':
                if (enableMethodInsight && CodeCompletionOptions.InsightEnabled)
                {
                    IInsightWindow insightWindow = editor.ShowInsightWindow(new MethodInsightProvider().ProvideInsight(editor));
                    if (insightWindow != null && insightHandler != null)
                    {
                        insightHandler.InitializeOpenedInsightWindow(editor, insightWindow);
                        insightHandler.HighlightParameter(insightWindow, -1);                                 // disable highlighting
                    }
                    return(CodeCompletionKeyPressResult.Completed);
                }
                break;

            case '[':
                if (enableIndexerInsight && CodeCompletionOptions.InsightEnabled)
                {
                    IInsightWindow insightWindow = editor.ShowInsightWindow(new IndexerInsightProvider().ProvideInsight(editor));
                    if (insightWindow != null && insightHandler != null)
                    {
                        insightHandler.InitializeOpenedInsightWindow(editor, insightWindow);
                    }
                    return(CodeCompletionKeyPressResult.Completed);
                }
                break;

            case '<':
                if (enableXmlCommentCompletion)
                {
                    new CommentCompletionItemProvider().ShowCompletion(editor);
                    return(CodeCompletionKeyPressResult.Completed);
                }
                break;

            case '.':
                if (enableDotCompletion)
                {
                    new DotCodeCompletionItemProvider().ShowCompletion(editor);
                    return(CodeCompletionKeyPressResult.Completed);
                }
                break;

            case ' ':
                if (CodeCompletionOptions.KeywordCompletionEnabled)
                {
                    string word = editor.GetWordBeforeCaret();
                    if (!string.IsNullOrEmpty(word))
                    {
                        if (HandleKeyword(editor, word))
                        {
                            return(CodeCompletionKeyPressResult.Completed);
                        }
                    }
                }
                break;
            }
            return(CodeCompletionKeyPressResult.None);
        }
        static IEnumerable <AddUsingAction> GetAddUsingActionsForUnknownClass(IClass callingClass, string unknownClassName, ITextEditor editor)
        {
            if (callingClass == null)
            {
                yield break;
            }
            IProjectContent pc = callingClass.ProjectContent;

            if (!pc.Language.RefactoringProvider.IsEnabledForFile(callingClass.CompilationUnit.FileName))
            {
                yield break;
            }
            List <IClass> searchResults = new List <IClass>();

            SearchAllClassesWithName(searchResults, pc, unknownClassName, pc.Language);
            foreach (IProjectContent rpc in pc.ReferencedContents)
            {
                SearchAllClassesWithName(searchResults, rpc, unknownClassName, pc.Language);
            }
            foreach (IClass c in searchResults)
            {
                string newNamespace = c.Namespace;
                yield return(new AddUsingAction(callingClass.CompilationUnit, editor, newNamespace));
            }
        }
 public static IEnumerable <AddUsingAction> GetAddUsingActions(ResolveResult symbol, ITextEditor editor)
 {
     if (symbol is UnknownIdentifierResolveResult)
     {
         return(GetAddUsingActions((UnknownIdentifierResolveResult)symbol, editor));
     }
     else if (symbol is UnknownConstructorCallResolveResult)
     {
         return(GetAddUsingActions((UnknownConstructorCallResolveResult)symbol, editor));
     }
     return(new AddUsingAction[0]);
 }
Beispiel #39
0
 /// <summary>
 /// Generates the completion list.
 /// </summary>
 public abstract ICompletionItemList GenerateCompletionList(ITextEditor editor);
 public static IEnumerable <AddUsingAction> GetAddUsingActions(UnknownIdentifierResolveResult rr, ITextEditor textArea)
 {
     return(GetAddUsingActionsForUnknownClass(rr.CallingClass, rr.Identifier, textArea));
 }
Beispiel #41
0
 public override void ShowCompletion(ITextEditor editor)
 {
     TextEditorPassedToShowCompletion = editor;
 }
Beispiel #42
0
 public virtual ExpressionResult GetExpression(ITextEditor editor)
 {
     return(GetExpressionFromOffset(editor, editor.Caret.Offset));
 }
 public void Attach(ITextEditor editor)
 {
     Attach(textEditorFactory.CreateTextEditor(editor));
 }
Beispiel #44
0
 public override ICompletionItemList GenerateCompletionList(ITextEditor editor)
 {
     throw new NotImplementedException();
 }
Beispiel #45
0
 /// <summary>
 /// Inserts code at the line before target AST node.
 /// </summary>
 public static void InsertCodeBefore(this ITextEditor editor, AbstractNode target, AbstractNode insert)
 {
     InsertCode(editor, target, insert, editor.Document.GetPreviousLineEndOffset(target.StartLocation), false);
 }
 public static void ClearSelection(this ITextEditor editor)
 {
     editor.Select(editor.Document.PositionToOffset(editor.Caret.Position), 0);
 }
Beispiel #47
0
        private (ISegment whitespace, int offset, char character) GetPreviousBracketInfo(ITextEditor editor, int offset)
        {
            if (offset >= editor.Document.TextLength)
            {
                offset = editor.Document.TextLength - 1;
            }

            if (offset >= 0)
            {
                var location = editor.Document.GetLocation(offset);
                var line     = editor.Document.Lines[location.Line];

                var previousBracket = editor.Document.GetLastCharMatching(c => c == '{' || c == '}', line.Offset, 0);

                if (previousBracket.index != -1)
                {
                    var previousBracketLocation = editor.Document.GetLocation(previousBracket.index);
                    var previousBracketLine     = editor.Document.Lines[previousBracketLocation.Line];

                    return(editor.Document.GetWhitespaceAfter(previousBracketLine.Offset), previousBracket.index, previousBracket.character);
                }
            }

            return(null, -1, '\0');
        }
Beispiel #48
0
 protected abstract void Run(ITextEditor editor, IBookmarkMargin bookmarkMargin);
Beispiel #49
0
        public bool AfterTextInput(ITextEditor editor, string inputText)
        {
            if (inputText == "\n")
            {
                var previousBracketInfo = GetPreviousBracketInfo(editor, editor.Offset - 1);

                if (previousBracketInfo.whitespace != null)
                {
                    Indent(editor, editor.Line, previousBracketInfo.whitespace, previousBracketInfo.character);
                }

                ConditionalIndent(editor, true);
            }
            else if (inputText == "{" || inputText == "}" || inputText == ";")
            {
                var prevLine = editor.PreviousLine();

                if (prevLine != null)
                {
                    var lastCharInfo = editor.Document.GetLastNonWhiteSpaceCharBefore(prevLine.EndOffset, prevLine.Offset);

                    if (!(inputText == "{" && lastCharInfo.character == '{'))
                    {
                        if (inputText == "{" || inputText == "}")
                        {
                            var lastBracketWhitespaceInfo = GetPreviousBracketInfo(editor, editor.Offset - 2);

                            Indent(editor, editor.Line, lastBracketWhitespaceInfo.whitespace, lastBracketWhitespaceInfo.character);
                        }
                        else
                        {
                            var lastBracketWhitespaceInfo = GetPreviousBracketInfo(editor, editor.Offset - 1);

                            if (lastCharInfo.character == ')')
                            {
                                Indent(editor, editor.Line, lastBracketWhitespaceInfo.whitespace, lastBracketWhitespaceInfo.character, lastBracketWhitespaceInfo.character == '{' ? 2 : 1, true);
                            }
                            else
                            {
                                var previousLineText = editor.PreviousLineText().Trim();

                                if (previousLineText.EndsWith("else"))
                                {
                                    var lineText = editor.CurrentLineText();

                                    if (!lineText.Contains("{"))
                                    {
                                        Indent(editor, editor.Line, lastBracketWhitespaceInfo.whitespace, lastBracketWhitespaceInfo.character, lastBracketWhitespaceInfo.character == '{' ? 2 : 1, true);
                                    }
                                }
                                else
                                {
                                    Indent(editor, editor.Line, lastBracketWhitespaceInfo.whitespace, lastBracketWhitespaceInfo.character);
                                }
                            }
                        }
                    }
                }
                else
                {
                    Indent(editor, editor.Line, null, null);
                }
            }

            return(false);
        }
Beispiel #50
0
 /// <summary>
 /// Inserts code at the next line after target AST node.
 /// </summary>
 public static void InsertCodeAfter(this ITextEditor editor, AbstractNode target, AbstractNode insert, bool updateCaretPos = false)
 {
     InsertCode(editor, target, insert, editor.Document.GetLineEndOffset(target.EndLocation), updateCaretPos);
 }
        public override ITextSegmentStyled FindStyledTextSegment(ITextEditor textEditor, ITextSegment textSegment, ITextDocument document, int startIndex, int length, int textColumnIndex)
        {
            var text = textSegment.GetText(textColumnIndex);

            if (startIndex >= text.Length)
            {
                return(null);
            }

            foreach (var word in this.WordList)
            {
                for (var i = 0; i < word.Length; i++)
                {
                    if (word[i] != text[startIndex])
                    {
                        continue;
                    }

                    var found = true;

                    var left = i - 1;
                    for (; left >= 0; left--)
                    {
                        var relativeIndex = startIndex - (i - left);

                        if (relativeIndex < 0)
                        {
                            found = false;
                            break;
                        }

                        var c = text[relativeIndex];
                        if (word[left] != c)
                        {
                            found = false;
                            break;
                        }
                    }

                    if (found == false)
                    {
                        break;
                    }

                    left = Math.Max(0, left);

                    var right = i + 1;
                    for (; right < word.Length; right++)
                    {
                        var relativeIndex = startIndex + (right - i);

                        if (relativeIndex >= text.Length)
                        {
                            found = false;
                            break;
                        }

                        var c = text[relativeIndex];
                        if (word[right] != c)
                        {
                            found = false;
                            break;
                        }
                    }

                    if (found)
                    {
                        var newTextSegment = document.CreateStyledTextSegment(this);

                        var relativeIndex = startIndex - (i - left);
                        newTextSegment.Index = relativeIndex;
                        newTextSegment.SetLength(textColumnIndex, right - left);

                        newTextSegment.Object = word;

                        return(newTextSegment);
                    }
                }
            }

            return(null);
        }
Beispiel #52
0
 public bool BeforeTextInput(ITextEditor editor, string inputText)
 {
     return(false);
 }
 public override Color GetColorBack(ITextEditor textEditor)
 {
     return(textEditor.Settings.ColorHighlightBack);
 }
Beispiel #54
0
 protected override bool Refactor(ITextEditor editor, XDocument document)
 {
     RemoveRecursive(document.Root, "Margin");
     return(true);
 }
Beispiel #55
0
 public override void Attach(ITextEditor editor)
 {
     //CSharpBackgroundCompiler.Init();
 }
 public override Color GetColorFore(ITextEditor textEditor)
 {
     return(textEditor.Settings.ColorHighlightFore);
 }
 ICodeCompletionBinding CreateBinding(ITextEditor editor)
 {
     return(SD.LanguageService.GetLanguageByExtension(".cs")
            .CreateCompletionBinding(FindExpressionToComplete(editor), CreateContext(editor)));
 }
        public TextEditorContextMenuStrip(ITextEditor editor)
        {
            _editor = editor;

            #region Edit commands

            _undo = CreateMenuItem("&Undo", Undo);
            _redo = CreateMenuItem("&Redo", Redo);

            _cut    = CreateMenuItem("Cu&t", Cut);
            _copy   = CreateMenuItem("&Copy", Copy);
            _paste  = CreateMenuItem("&Paste", Paste);
            _delete = CreateMenuItem("&Delete", Delete);

            _selectAll = CreateMenuItem("Select &All", SelectAll);

            #endregion

            #region Options

            _optionsDivider = CreateSeparator();

            _options = CreateMenuItem("&Options");
            _options.DropDown.Closing += OptionsDropDownOnClosing;

            _showLineNumbers = CreateOptionsMenuItem("Show &Line Numbers", ToggleShowLineNumbers);
            _showWhiteSpace  = CreateOptionsMenuItem("Show &Whitespace", ToggleShowWhiteSpace);
            _wordWrap        = CreateOptionsMenuItem("Word &Wrap", ToggleWordWrap);

            #region Ruler

            _ruler = CreateMenuItem("&Ruler");
            _ruler.DropDown.Closing += OptionsDropDownOnClosing;

            _none             = CreateRulerMenuItem("None");
            _seventy          = CreateRulerMenuItem(70);
            _seventyEight     = CreateRulerMenuItem(78);
            _eighty           = CreateRulerMenuItem(80);
            _oneHundred       = CreateRulerMenuItem(100);
            _oneHundredTwenty = CreateRulerMenuItem(120);

            _ruler.DropDownItems.AddRange(new ToolStripItem[]
            {
                _none,
                CreateSeparator(),
                _seventy,
                _seventyEight,
                _eighty,
                _oneHundred,
                _oneHundredTwenty,
            });

            #endregion

            _options.DropDownItems.AddRange(new ToolStripItem[]
            {
                _showLineNumbers,
                _showWhiteSpace,
                CreateSeparator(),
                _wordWrap,
                _ruler,
            });

            #endregion

            #region Top-level menu

            base.Items.AddRange(new ToolStripItem[]
            {
                _undo,
                _redo,
                CreateSeparator(),
                _cut,
                _copy,
                _paste,
                _delete,
                CreateSeparator(),
                _selectAll,
                _optionsDivider,
                _options,
            });

            Opened += (sender, args) => SetMenuItemStates();

            #endregion
        }
 public CodeCompletionKeyPressResult HandleKeyPress(ITextEditor editor, char ch)
 {
     // We use HandleKeyPressed instead.
     return(CodeCompletionKeyPressResult.None);
 }
 protected abstract bool Refactor(ITextEditor editor, XDocument document);