Exemplo n.º 1
0
        public override IEnumerable<CodeSuggestion> GetSuggestions(TextLocation location)
        {
            var node = File.CompilationUnit.GetClosestNodeBeforeLocation(location);
            var scope = node.GetDeclaringScope();

            while (true)
            {
                if (node is Statement)
                    break;

                var reference = node as MemberReferenceExpression;
                if (reference != null)
                {
                    var result = reference.Target.Resolve(scope);
                    if (result.ScopeProvider != null)
                    {
                        foreach (var definition in result.ScopeProvider.GetScope().GetDefinitions())
                            yield return new CodeSuggestion(definition.Name, definition.FullName, definition.Name);
                        yield break;
                    }
                }

                node = node.Parent;
            }

            foreach (var definition in scope.GetAllDefinitions())
            {
                yield return new CodeSuggestion(definition.Name, definition.FullName, definition.Name);
            }
        }
Exemplo n.º 2
0
 /// <summary>
 /// Write a text in a label.
 /// </summary>
 /// <param name="line"></param>
 /// <param name="location"></param>
 public static void writeLine(Line line, TextLocation location)
 {
     int textLength = line.Text.Length;
     switch (location)
     {
         case TextLocation.Up:
             writeLine(line, new Rect(
                      (Screen.width - GUI.skin.label.fontSize / 2 * textLength) / 2,
                       0,
                       Screen.width,
                       GUI.skin.label.fontSize * 2
             ));
             break;
         case TextLocation.Middle:
             writeLine(line, new Rect(
                      (Screen.width - GUI.skin.label.fontSize / 2 * textLength) / 2,
                       Screen.height / 2 - GUI.skin.label.fontSize,
                       Screen.width,
                       GUI.skin.label.fontSize * 2
             ));
             break;
         case TextLocation.Down:
             writeLine(line, new Rect(
                      (Screen.width - GUI.skin.label.fontSize / 2 * textLength) / 2,
                       Screen.height - GUI.skin.label.fontSize * 2,
                       Screen.width,
                       GUI.skin.label.fontSize * 2
             ));
             break;
     }
 }
Exemplo n.º 3
0
        public IEnumerable<ICompletionData> CreateProvider(AutoCompleteRequest request)
        {
            var editorText = request.Buffer ?? "";
            var filename = request.FileName;
            var partialWord = request.WordToComplete ?? "";

            var doc = new ReadOnlyDocument(editorText);
            var loc = new TextLocation(request.Line, request.Column - partialWord.Length);
            int cursorPosition = doc.GetOffset(loc);
            //Ensure cursorPosition only equals 0 when editorText is empty, so line 1,column 1
            //completion will work correctly.
            cursorPosition = Math.Max(cursorPosition, 1);
            cursorPosition = Math.Min(cursorPosition, editorText.Length);

            var res = _parser.ParsedContent(editorText, filename);
            var rctx = res.UnresolvedFile.GetTypeResolveContext(res.Compilation, loc);

            ICompletionContextProvider contextProvider = new DefaultCompletionContextProvider(doc, res.UnresolvedFile);
            var engine = new CSharpCompletionEngine(doc, contextProvider, new CompletionDataFactory(partialWord), res.ProjectContent, rctx)
                {
                    EolMarker = Environment.NewLine
                };

            _logger.Debug("Getting Completion Data");

            IEnumerable<ICompletionData> data = engine.GetCompletionData(cursorPosition, true);
            _logger.Debug("Got Completion Data");

            return data.Where(d => d != null && d.DisplayText.IsValidCompletionFor(partialWord))
                       .FlattenOverloads()
                       .RemoveDupes()
                       .OrderBy(d => d.DisplayText);
        }
		public GenerateNamespaceImport GetResult (IUnresolvedFile unit, IType type, MonoDevelop.Ide.Gui.Document doc)
		{
			GenerateNamespaceImport result;
			if (cache.TryGetValue (type.Namespace, out result))
				return result;
			result = new GenerateNamespaceImport ();
			cache[type.Namespace] = result;
			TextEditorData data = doc.Editor;
			
			result.InsertNamespace  = false;
			var loc = new TextLocation (data.Caret.Line, data.Caret.Column);
			foreach (var ns in RefactoringOptions.GetUsedNamespaces (doc, loc)) {
				if (type.Namespace == ns) {
					result.GenerateUsing = false;
					return result;
				}
			}
			
			result.GenerateUsing = true;
			string name = type.Name;
			
			foreach (string ns in RefactoringOptions.GetUsedNamespaces (doc, loc)) {
				if (doc.Compilation.MainAssembly.GetTypeDefinition (ns, name, type.TypeParameterCount) != null) {
					result.GenerateUsing = false;
					result.InsertNamespace = true;
					return result;
				}
			}
			return result;
		}
Exemplo n.º 5
0
        public static BracketSearchResult SearchBrackets(TextDocument doc, int caretOffset, TextLocation caret)
        {
            var caretLocation = new CodeLocation(caret.Column, caret.Line);
            try
            {
                if (caretOffset < 1 || caretOffset>=doc.TextLength-2)
                    return null;

                // Search backward
                DToken lastToken=null;
                var tk_start = SearchBackward(doc, caretOffset, caretLocation,out lastToken);

                if (tk_start == null)
                    return null;

                // Search forward
                var tk_end = SearchForward(doc,
                    doc.GetOffset(lastToken.EndLocation.Line,lastToken.EndLocation.Column),
                    lastToken.EndLocation,
                    getOppositeBracketToken(tk_start.Kind));

                if (tk_end == null)
                    return null;

                int start = doc.GetOffset(tk_start.Location.Line, tk_start.Location.Column),
                    end = doc.GetOffset(tk_end.Location.Line, tk_end.Location.Column);

                return new BracketSearchResult(start, 1, end, 1);
            }
            catch { return null; }
        }
		void CreateWidget (IEnumerable<CodeAction> fixes, TextLocation loc)
		{
			Fixes = fixes;
			if (!QuickTaskStrip.EnableFancyFeatures)
				return;
			var editor = document.Editor;
			if (editor == null || editor.Parent == null || !editor.Parent.IsRealized)
				return;

			if (!fixes.Any ()) {
				ICSharpCode.NRefactory.TypeSystem.DomRegion region;
				var resolveResult = document.GetLanguageItem (editor.Caret.Offset, out region);
				if (resolveResult != null) {
					var possibleNamespaces = ResolveCommandHandler.GetPossibleNamespaces (document, resolveResult);
					if (!possibleNamespaces.Any ())
						return;
				} else
					return;
			}
			var container = editor.Parent.Parent as TextEditorContainer;
			if (container == null) 
				return;
			if (widget == null) {
				widget = new CodeActionWidget (this, Document);
				container.AddTopLevelWidget (widget,
					2 + (int)editor.Parent.TextViewMargin.XOffset,
					-2 + (int)editor.Parent.LineToY (document.Editor.Caret.Line));
			} else {
				container.MoveTopLevelWidget (widget,
					2 + (int)editor.Parent.TextViewMargin.XOffset,
					-2 + (int)editor.Parent.LineToY (document.Editor.Caret.Line));
			}
			widget.Show ();
			widget.SetFixes (fixes, loc);
		}
Exemplo n.º 7
0
		public ResolveResult Resolve(ParseInformation parseInfo, TextLocation location, ICompilation compilation, CancellationToken cancellationToken)
		{
			var decompiledParseInfo = parseInfo as ILSpyFullParseInformation;
			if (decompiledParseInfo == null)
				throw new ArgumentException("ParseInfo does not have SyntaxTree");
			return ResolveAtLocation.Resolve(compilation, null, decompiledParseInfo.SyntaxTree, location, cancellationToken);
		}
Exemplo n.º 8
0
		public static bool TryGetFormattingParameters(CSharpInvocationResolveResult invocationResolveResult, InvocationExpression invocationExpression,
		                                     		  out Expression formatArgument, out TextLocation formatStart, out IList<Expression> arguments,
		                                              Func<IParameter, Expression, bool> argumentFilter)
		{
			if (argumentFilter == null)
				argumentFilter = (p, e) => true;

			formatArgument = null;
			formatStart = default(TextLocation);
			arguments = new List<Expression>();
			var argumentToParameterMap = invocationResolveResult.GetArgumentToParameterMap();
			var resolvedParameters = invocationResolveResult.Member.Parameters;
			var allArguments = invocationExpression.Arguments.ToArray();
			for (int i = 0; i < allArguments.Length; i++) {
				var parameterIndex = argumentToParameterMap[i];
				if (parameterIndex < 0 || parameterIndex >= resolvedParameters.Count) {
					// No valid mapping for this parameter, skip it
					continue;
				}
				var parameter = resolvedParameters[parameterIndex];
				var argument = allArguments[i];
				if (parameter.Type.IsKnownType(KnownTypeCode.String) && parameterNames.Contains(parameter.Name)) {
					formatArgument = argument;
					formatStart = argument.StartLocation;
				} else if ((formatArgument != null || parameter.IsParams) && argumentFilter(parameter, argument)) {
					arguments.Add(argument);
				}
			}
			return formatArgument != null;
		}
Exemplo n.º 9
0
 public DebuggerPopup(DebuggerTooltipControl parentControl, TextLocation logicalPosition, bool showPins = true)
 {
     this.contentControl = new DebuggerTooltipControl(parentControl, logicalPosition, showPins);
     this.contentControl.containingPopup = this;
     this.Child = this.contentControl;
     this.IsLeaf = false;
 }
Exemplo n.º 10
0
        /// <summary>
        /// Executes the action on a certain <see cref="TextArea"/>.
        /// </summary>
        /// <param name="textArea">The text area on which to execute the action.</param>
        public override void Execute(TextArea textArea)
        {
            LineSegment curLine;
              TextLocation newPos = textArea.Caret.Position;
              bool jumpedIntoFolding;
              do
              {
            curLine = textArea.Document.GetLineSegment(newPos.Y);
            newPos.X = curLine.Length;

            List<Fold> foldings = textArea.Document.FoldingManager.GetFoldsFromPosition(newPos.Y, newPos.X);
            jumpedIntoFolding = false;
            foreach (Fold fold in foldings)
            {
              if (fold.IsFolded)
              {
            newPos = new TextLocation(fold.EndColumn, fold.EndLine);
            jumpedIntoFolding = true;
            break;
              }
            }
              } while (jumpedIntoFolding);

              if (newPos != textArea.Caret.Position)
              {
            textArea.Caret.Position = newPos;
            textArea.SetDesiredColumn();
              }
        }
        public static OmniSharpRefactoringContext GetContext(BufferParser bufferParser, Request request)
        {
            var q = bufferParser.ParsedContent(request.Buffer, request.FileName);
            var resolver = new CSharpAstResolver(q.Compilation, q.SyntaxTree, q.UnresolvedFile);
            var doc = new StringBuilderDocument(request.Buffer);
            var location = new TextLocation(request.Line, request.Column);
            OmniSharpRefactoringContext refactoringContext;
            if(request is CodeActionRequest)
            {
                var car = request as CodeActionRequest;
                if(car.SelectionStartColumn.HasValue)
                {
                    var startLocation
                        = new TextLocation(car.SelectionStartLine.Value, car.SelectionStartColumn.Value);
                    var endLocation
                        = new TextLocation(car.SelectionEndLine.Value, car.SelectionEndColumn.Value);

                    refactoringContext = new OmniSharpRefactoringContext(doc, resolver, location, startLocation, endLocation);
                }
                else
                {
                    refactoringContext = new OmniSharpRefactoringContext(doc, resolver, location);
                }
            }
            else
            {
                refactoringContext = new OmniSharpRefactoringContext(doc, resolver, location);
            }
            refactoringContext.Services.AddService (typeof(NamingConventionService), new DefaultNameService ());
            return refactoringContext;
        }
		public DebuggerTooltipControl(TextLocation logicalPosition)
		{
			this.logicalPosition = logicalPosition;
			InitializeComponent();
			
			Loaded += new RoutedEventHandler(OnLoaded);
		}
Exemplo n.º 13
0
        public DebuggerTooltipControl(TextLocation logicalPosition)
        {
            this.logicalPosition = logicalPosition;
            InitializeComponent();

            Loaded += OnLoaded;
        }
 protected AbstractMessage(AbstractMessage aMsg)
 {
     this.code = aMsg.code;
     this.location = aMsg.location;
     this.message = aMsg.message;
     this.extra_info = aMsg.extra_info;
 }
Exemplo n.º 15
0
		public override IEnumerable<MonoDevelop.CodeActions.CodeAction> GetActions (MonoDevelop.Ide.Gui.Document document, object refactoringContext, TextLocation loc, CancellationToken cancellationToken)
		{
			var context = refactoringContext as MDRefactoringContext;
			if (context == null)
				return Enumerable.Empty<MonoDevelop.CodeActions.CodeAction> ();
			return GetActions (context);
		}
		void CreateWidget (IEnumerable<CodeAction> fixes, TextLocation loc)
		{
			this.loc = loc;
			var editor = document.Editor;
			var container = editor.Parent;
			var point = editor.Parent.LocationToPoint (loc);
			point.Y += (int)editor.LineHeight;
			if (widget == null) {
				widget = new CodeActionWidget (this, Document);
				container.AddTopLevelWidget (
					widget,
					point.X,
					point.Y
				);
				widget.Show ();
			} else {
				if (!widget.Visible)
					widget.Show ();
				container.MoveTopLevelWidget (
					widget,
					point.X,
					point.Y
				);
			}
			widget.SetFixes (fixes, loc);
		}
Exemplo n.º 17
0
        public static ResolveResult Resolve(Lazy<ICompilation> compilation, CSharpUnresolvedFile unresolvedFile, SyntaxTree syntaxTree, TextLocation location, out AstNode node,
		                                    CancellationToken cancellationToken = default(CancellationToken))
        {
            node = syntaxTree.GetNodeAt(location);
            if (node == null || node is ArrayInitializerExpression)
                return null;
            if (node.Parent is UsingAliasDeclaration && node.Role == UsingAliasDeclaration.AliasRole) {
                var r = new CSharpAstResolver(compilation.Value, syntaxTree, unresolvedFile);
                return r.Resolve(((UsingAliasDeclaration)node.Parent).Import, cancellationToken);
            }
            if (CSharpAstResolver.IsUnresolvableNode(node)) {
                if (node is Identifier) {
                    node = node.Parent;
                } else if (node.NodeType == NodeType.Token) {
                    if (node.Parent is IndexerExpression || node.Parent is ConstructorInitializer) {
                        // There's no other place where one could hover to see the indexer's tooltip,
                        // so we need to resolve it when hovering over the '[' or ']'.
                        // For constructor initializer, the same applies to the 'base'/'this' token.
                        node = node.Parent;
                    } else {
                        return null;
                    }
                } else {
                    // don't resolve arbitrary nodes - we don't want to show tooltips for everything
                    return null;
                }
            } else {
                // It's a resolvable node.
                // However, we usually don't want to show the tooltip everywhere
                // For example, hovering with the mouse over an empty line between two methods causes
                // node==TypeDeclaration, but we don't want to show any tooltip.

                if (!node.GetChildByRole(Roles.Identifier).IsNull) {
                    // We'll suppress the tooltip for resolvable nodes if there is an identifier that
                    // could be hovered over instead:
                    return null;
                }
            }

            if (node == null)
                return null;

            if (node.Parent is ObjectCreateExpression && node.Role == Roles.Type) {
                node = node.Parent;
            }

            InvocationExpression parentInvocation = null;
            if ((node is IdentifierExpression || node is MemberReferenceExpression || node is PointerReferenceExpression) && node.Role != Roles.Argument) {
                // we also need to resolve the invocation
                parentInvocation = node.Parent as InvocationExpression;
            }

            // TODO: I think we should provide an overload so that an existing CSharpAstResolver can be reused
            CSharpAstResolver resolver = new CSharpAstResolver(compilation.Value, syntaxTree, unresolvedFile);
            ResolveResult rr = resolver.Resolve(node, cancellationToken);
            if (rr is MethodGroupResolveResult && parentInvocation != null)
                return resolver.Resolve(parentInvocation);
            else
                return rr;
        }
			void CheckSegments(IList<IFormatStringSegment> segments, TextLocation formatStart, IList<Expression> formatArguments, AstNode anchor)
			{
				int argumentCount = formatArguments.Count;
				foreach (var segment in segments) {
					var errors = segment.Errors.ToList();
					var formatItem = segment as FormatItem;
					if (formatItem != null) {
						var segmentEnd = new TextLocation(formatStart.Line, formatStart.Column + segment.EndLocation + 1);
						var segmentStart = new TextLocation(formatStart.Line, formatStart.Column + segment.StartLocation + 1);
						if (formatItem.Index >= argumentCount) {
							var outOfBounds = context.TranslateString("The index '{0}' is out of bounds of the passed arguments");
							AddIssue(segmentStart, segmentEnd, string.Format(outOfBounds, formatItem.Index));
						}
						if (formatItem.HasErrors) {
							var errorMessage = string.Join(Environment.NewLine, errors.Select(error => error.Message).ToArray());
							string messageFormat;
							if (errors.Count > 1) {
								messageFormat = context.TranslateString("Multiple:\n{0}");
							} else {
								messageFormat = context.TranslateString("{0}");
							}
							AddIssue(segmentStart, segmentEnd, string.Format(messageFormat, errorMessage));
						}
					} else if (segment.HasErrors) {
						foreach (var error in errors) {
							var errorStart = new TextLocation(formatStart.Line, formatStart.Column + error.StartLocation + 1);
							var errorEnd = new TextLocation(formatStart.Line, formatStart.Column + error.EndLocation + 1);
							AddIssue(errorStart, errorEnd, error.Message);
						}
					}
				}
			}
Exemplo n.º 19
0
		void AnchorDeleted(object sender, EventArgs e)
		{
			// the anchor just became invalid, so don't try to use it again
			location = TextLocation.Empty;
			anchor = null;
			RemoveMark();
		}
Exemplo n.º 20
0
 public static void Message(this IErrorReporter reporter, int code, string file, TextLocation location, params object[] args)
 {
     var msg = Messages.Get(code);
     if (msg == null)
         reporter.InternalError("Message " + code + " does not exist" + (args.Length > 0 ? " (arguments were " + string.Join(", ", args) + ")" : "") + ".", file, location);
     reporter.Message(msg.Item1, code, file, location, msg.Item2, args);
 }
		public void LocationJumpedToAfterInsert()
		{
			int column = 1;
			int line = 3;
			var expectedLocation = new TextLocation(column, line);
			Assert.AreEqual(expectedLocation, textEditor.LocationJumpedTo);
		}
Exemplo n.º 22
0
        public TextLocation ApplyTo(TextLocation location, bool negativeTracking, out bool updated)
        {
            if ((this.Start > location) || (negativeTracking && (this.Start == location)))
            {
                // This change happened after the location given, so it doesn't move.
                updated = false;
                return location;
            }

            updated = true;
            if (this.OldEnd >= location)
            {
                // The location is within the modified portion of the edit, so the location
                // snaps to the start (negativeTracking) or end (!negativeTracking).
                return negativeTracking ? this.Start : this.NewEnd;
            }

            // The location is fully after the edit, so it moves according to the size of the
            // insertion/deletion.
            if (location.Line == this.OldEnd.Line)
            {
                // The location was on the old end line of the changed text, so both the line
                // and index get updated.
                return new TextLocation(this.NewEnd.Line, location.Index - this.OldEnd.Index + this.NewEnd.Index);
            }

            // The location was on a line not affected by the edit, so only the line changes
            return new TextLocation(location.Line + this.NewEnd.Line - this.OldEnd.Line, location.Index);
        }
Exemplo n.º 23
0
		public override void Execute(TextArea textArea)
		{
			TextLocation position = textArea.Caret.Position;
			List<FoldMarker> foldings = textArea.Document.FoldingManager.GetFoldedFoldingsWithEnd(position.Y);
			FoldMarker justBeforeCaret = null;
			foreach (FoldMarker fm in foldings) {
				if (fm.EndColumn == position.X) {
					justBeforeCaret = fm;
					break; // the first folding found is the folding with the smallest Startposition
				}
			}
			
			if (justBeforeCaret != null) {
				position.Y = justBeforeCaret.StartLine;
				position.X = justBeforeCaret.StartColumn;
			} else {
				if (position.X > 0) {
					--position.X;
				} else if (position.Y	> 0) {
					LineSegment lineAbove = textArea.Document.GetLineSegment(position.Y - 1);
					position = new TextLocation(lineAbove.Length, position.Y - 1);
				}
			}
			
			textArea.Caret.Position = position;
			textArea.SetDesiredColumn();
		}
Exemplo n.º 24
0
        public FindUsagesResponse FindUsages(FindUsagesRequest request)
        {
            var res = _parser.ParsedContent(request.Buffer, request.FileName);
            var loc = new TextLocation(request.Line, request.Column);
            var result = new ConcurrentBag<AstNode>();
            var findReferences = new FindReferences();
            ResolveResult resolveResult = ResolveAtLocation.Resolve(res.Compilation, res.UnresolvedFile, res.SyntaxTree, loc);
            if (resolveResult is LocalResolveResult)
            {
                var variable = (resolveResult as LocalResolveResult).Variable;
                findReferences.FindLocalReferences(variable, res.UnresolvedFile, res.SyntaxTree, res.Compilation, (node, rr) => result.Add(node), CancellationToken.None);
            }
            else
            {
                IEntity entity = null;
                if (resolveResult is TypeResolveResult)
                {
                    entity = (resolveResult as TypeResolveResult).Type.GetDefinition();
                }

                if (resolveResult is MemberResolveResult)
                {
                    entity = (resolveResult as MemberResolveResult).Member;
                }

                if (entity == null)
                {
                    return new FindUsagesResponse {Usages = new List<Usage>()};
                }
                var searchScopes = findReferences.GetSearchScopes(entity);

                var interesting = new List<CSharpUnresolvedFile>();

                foreach (var scope in searchScopes)
                {
                    var scopeInteresting = findReferences.GetInterestingFiles(scope, res.Compilation);
                    interesting.AddRange(scopeInteresting);
                }

                Parallel.ForEach(interesting, file =>
                    {
                        ParsedResult parsedResult = _parser.ParsedContent(
                            _solution.GetFile(file.FileName).Content.Text, file.FileName);
                        findReferences.FindReferencesInFile(searchScopes, file, parsedResult.SyntaxTree,
                                                            parsedResult.Compilation,
                                                            (node, rr) => result.Add(node), CancellationToken.None);
                    });

            }

            var usages = result.Select(node => new Usage
            {
                FileName = node.GetRegion().FileName,
                Text = node.Preview(_solution.GetFile(node.GetRegion().FileName)).Replace("'", "''"),
                Line = node.StartLocation.Line,
                Column = node.StartLocation.Column,
            });

            return new FindUsagesResponse { Usages = usages };
        }
Exemplo n.º 25
0
 public BookmarkBase(IMemberRef member, uint ilOffset, TextLocation location, TextLocation endLocation)
 {
     this.MemberReference = member;
     this.ilOffset = ilOffset;
     this.Location = location;
     this.EndLocation = endLocation;
 }
Exemplo n.º 26
0
 public BreakpointBookmark(IMemberRef member, TextLocation location, int functionToken, ILRange range, BreakpointAction action)
     : base(member, location)
 {
     this.action = action;
     this.FunctionToken = functionToken;
     this.ILRange = range;
     this.Tooltip = string.Format("Line:{0}, IL range:{1}-{2}", location.Line, range.From, range.To);
 }
Exemplo n.º 27
0
		public Token(int kind, int col, int line, string val)
		{
			this.kind         = kind;
			this.col          = col;
			this.line         = line;
			this.val          = val;
			this.endLocation  = new TextLocation(line, col + (val == null ? 1 : val.Length));
		}
 private OmniSharpRefactoringContext(IDocument document, CSharpAstResolver resolver, TextLocation location, TextLocation selectionStart, TextLocation selectionEnd) 
     : base(resolver, CancellationToken.None)
 {
     _document = document;
     _location = location;
     _selectionStart = selectionStart;
     _selectionEnd = selectionEnd;
 }
		public TestRefactoringContext (IDocument document, TextLocation location, CSharpAstResolver resolver) : base(resolver, CancellationToken.None)
		{
			this.doc = document;
			this.location = location;
			this.UseExplicitTypes = UseExplict;
			UseExplict = false;
			Services.AddService (typeof(NamingConventionService), new TestNameService ());
		}
Exemplo n.º 30
0
		IUnresolvedTypeDefinition IUnresolvedFile.GetTopLevelTypeDefinition(TextLocation location)
		{
			foreach (var td in topLevel) {
				if (td.Region.IsInside(location))
					return td;
			}
			return null;
		}
Exemplo n.º 31
0
 public AspNetDirective(TextLocation start) : base(start)
 {
     attributes = new XAttributeCollection(this);
 }
Exemplo n.º 32
0
 public AspNetDirective(TextLocation start, XName name) : this(start)
 {
     this.name = name;
 }
Exemplo n.º 33
0
 public override int GetOffset(TextLocation location)
 {
     return(doc.GetOffset(location));
 }
Exemplo n.º 34
0
 public AspNetRenderExpression(TextLocation start) : base(start)
 {
 }
Exemplo n.º 35
0
 public AspNetResourceExpression(TextLocation start) : base(start)
 {
 }
Exemplo n.º 36
0
 public SavepointEventArgs(TextLocation savepointLocation, VBLexerMemento state)
 {
     this.SavepointLocation = savepointLocation;
     this.State             = state;
 }
Exemplo n.º 37
0
 public override void Run(MonoDevelop.Ide.Gui.Document document, TextLocation loc)
 {
     Action.Fix();
 }
 /// <summary>
 /// Creates a new instance of <see cref="TextAreaUpdate"/>
 /// </summary>
 /// <param name="type">The type.</param>
 /// <param name="position">The position.</param>
 public TextAreaUpdate(TextAreaUpdateType type, TextLocation position)
 {
     _type     = type;
     _position = position;
 }
Exemplo n.º 39
0
 /// <summary>
 /// Returns true, if the given coordinates are in the node.
 /// </summary>
 /// <returns>
 /// True, if location is between StartLocation and EndLocation (exclusive); otherwise, false.
 /// </returns>
 public bool Contains(TextLocation location)
 {
     return(this.StartLocation <= location && location < this.EndLocation);
 }
Exemplo n.º 40
0
        private bool TextArea_KeyEventHandler(char ch)
        {
            if (!tsAutoInsertCode.Checked)
            {
                return(false);
            }
            try
            {
                var editor = VisualPascalABCProgram.MainForm.CurrentCodeFileDocument.TextEditor;
                var ta     = editor.ActiveTextAreaControl.TextArea;
                var doc    = ta.Document;

                /*if (ch == ' ')
                 * {
                 *  var caret1 = editor.ActiveTextAreaControl.Caret;
                 *  int start1 = TextUtilities.FindPrevWordStart(editor.Document, caret1.Offset);
                 *  var Text1 = editor.Document.GetText(start1, caret1.Offset - start1).TrimEnd();
                 *
                 *  if (Text1.ToLower().StartsWith("for") || Text1.ToLower().StartsWith("foreach"))
                 *  {
                 *      var curline = TextUtilities.GetLineAsString(editor.Document, caret1.Line);
                 *      var len = curline.TrimEnd().Length;
                 *      if (ta.Caret.Column == len)
                 *      {
                 *          doc.Replace(CurrentOffset(), curline.Length - len, " var");
                 *          ta.Caret.Column = ta.Caret.Column + 4;
                 *      }
                 *  }
                 *  return false;
                 * }*/
                /*if (ch == '(')
                 * {
                 *  var tl_beg = new TextLocation(ta.Caret.Column, ta.Caret.Line);
                 *  int offset = doc.PositionToOffset(tl_beg);
                 *  doc.Insert(offset, ")");
                 *  return false;
                 * }*/
                if (ch != '\n')
                {
                    return(false);
                }
                var caret = editor.ActiveTextAreaControl.Caret;
                int start = TextUtilities.FindPrevWordStart(editor.Document, caret.Offset);
                // Нужно, чтобы в Text было последнее слово в строке !!! Исключение - когда в следующей надо сделать просто сдвиг
                var Text        = editor.Document.GetText(start, caret.Offset - start).TrimEnd();
                var TextToLower = Text.ToLower();
                //var curStrEnd = TextUtilities.GetLineAsString(editor.Document, caret.Line).Substring(caret.Column);

                if (TextToLower == "begin")
                {
                    string cur, next, prev;
                    GetCurNextLines(out cur, out next, out prev);
                    // Ничего не надо делать если begin - не последнее слово в строке
                    var curStrEnd = cur.Substring(caret.Column);
                    if (!string.IsNullOrWhiteSpace(curStrEnd))
                    {
                        return(false);
                    }
                    // анализ предыдущей
                    var icur = Indent(cur);
                    if (cur.Trim().ToLower() == "begin" && (next == null || Indent(next) < icur || Indent(next) == icur && !next.TrimStart().ToLower().StartsWith("end"))) // значит, это единственное слово begin в строке
                    {
                        // Проанализируем предыдущий оператор по первому слову
                        var pst = prev?.TrimStart().ToLower();
                        if (pst != null)
                        {
                            //if (pst.StartsWith("if") || pst.StartsWith("for") || pst.StartsWith("loop") || pst.StartsWith("with") || pst.StartsWith("on") || pst.StartsWith("while") || pst.StartsWith("else") || pst.StartsWith("foreach")) // потом улучшу - для нескольких выборов
                            if (Regex.IsMatch(pst, "^(if|else|for|loop|while|foreach|with|on)"))
                            {
                                // Надо удалить в текущей строке пробелы чтобы выровнять begin по if
                                var iprev  = Indent(prev);
                                var tl_beg = new TextLocation(ta.Caret.Column, ta.Caret.Line);
                                int offset = doc.PositionToOffset(tl_beg);

                                var cls = doc.GetLineSegment(ta.Caret.Line);

                                // надо удалить всю строчку с begin и сформировать новую
                                doc.Replace(cls.Offset, cls.Length, Spaces(iprev) + "begin");
                                ta.Caret.Column = iprev + 5;
                                icur            = iprev;
                            }
                        }
                    }

                    ta.InsertString("\n" + Spaces(icur + 2));
                    if (next == null || Indent(next) < icur || Indent(next) == icur && !next.TrimStart().ToLower().StartsWith("end"))
                    {
                        var tl_beg = new TextLocation(ta.Caret.Column, ta.Caret.Line);
                        int offset = doc.PositionToOffset(tl_beg);
                        var send   = "\n" + Spaces(icur) + "end";
                        if (next == null && (prev == null || !(prev.TrimStart().ToLower().StartsWith("procedure") || prev.TrimStart().ToLower().StartsWith("function"))))
                        {
                            send += ".";
                        }
                        else
                        {
                            send += ";";
                        }
                        doc.Insert(offset, send);
                    }
                    return(true);
                }

                else if (TextToLower == "repeat") // repeat .. until
                {
                    string cur, next, prev;
                    GetCurNextLines(out cur, out next, out prev);
                    if (!string.IsNullOrWhiteSpace(cur.Substring(caret.Column)))
                    {
                        return(false);
                    }
                    var icur = Indent(cur);
                    ta.InsertString("\n" + Spaces(icur + 2));
                    if (next == null || Indent(next) < icur || Indent(next) == icur && !next.TrimStart().ToLower().StartsWith("until"))
                    {
                        var tl_beg = new TextLocation(ta.Caret.Column, ta.Caret.Line);
                        int offset = doc.PositionToOffset(tl_beg);
                        var send   = "\n" + Spaces(icur) + "until ;";
                        doc.Insert(offset, send);
                    }
                    return(true);
                }

                else if (Regex.IsMatch(TextToLower, "class|record")) // class .. end, record .. end
                {
                    string cur, next, prev;
                    GetCurNextLines(out cur, out next, out prev);
                    if (!string.IsNullOrWhiteSpace(cur.Substring(caret.Column)))
                    {
                        return(false);
                    }
                    var icur = Indent(cur);
                    ta.InsertString("\n" + Spaces(icur + 2));
                    if (next == null || Indent(next) < icur || Indent(next) == icur && !next.TrimStart().ToLower().StartsWith("until"))
                    {
                        var tl_beg = new TextLocation(ta.Caret.Column, ta.Caret.Line);
                        int offset = doc.PositionToOffset(tl_beg);
                        var send   = "\n" + Spaces(icur) + "end;";
                        doc.Insert(offset, send);
                    }
                    return(true);
                }

                else if (TextToLower == "of")
                {
                    string cur, next, prev;
                    GetCurNextLines(out cur, out next, out prev);
                    if (!string.IsNullOrWhiteSpace(cur.Substring(caret.Column)))
                    {
                        return(false);
                    }
                    var icur = Indent(cur);
                    ta.InsertString("\n" + Spaces(icur + 2));
                    if (cur.TrimStart().ToLower().StartsWith("case") && next == null || Indent(next) < icur || Indent(next) == icur && !next.TrimStart().ToLower().StartsWith("end"))
                    {
                        var tl_beg = new TextLocation(ta.Caret.Column, ta.Caret.Line);
                        int offset = doc.PositionToOffset(tl_beg);
                        var send   = "\n" + Spaces(icur) + "end;";
                        doc.Insert(offset, send);
                    }
                    return(true);
                }

                else if (Regex.IsMatch(TextToLower, "then|else|do|try|except|finally|var"))
                {
                    if (ta.Caret.Line > 0 && TextToLower == "else")
                    {
                        var prevSeg = doc.GetLineSegment(ta.Caret.Line - 1);
                        var prev    = GetLine(ta.Caret.Line - 1).TrimEnd();

                        if (prev[prev.Length - 1] == ';')
                        {
                            doc.Replace(prevSeg.Offset + prevSeg.Length - 1, 1, "");
                        }
                    }

                    var cur  = GetLine(ta.Caret.Line);
                    var icur = Indent(cur);
                    ta.InsertString("\n" + Spaces(icur + 2));

                    return(true);
                }

                else
                {
                    string cur, next, prev;
                    GetCurNextLines(out cur, out next, out prev);
                    if (ta.Caret.Column >= cur.Length)
                    {
                        var prevTrimEnd = prev.TrimEnd();
                        // если prev заканчивается на then, а cur не начинается с begin, то отступ назад
                        if ((prevTrimEnd.EndsWith("then", StringComparison.InvariantCultureIgnoreCase) ||
                             prevTrimEnd.EndsWith("else", StringComparison.InvariantCultureIgnoreCase) ||
                             prevTrimEnd.EndsWith("do", StringComparison.InvariantCultureIgnoreCase))
                            &&
                            !(cur.TrimStart().StartsWith("begin", StringComparison.InvariantCultureIgnoreCase)))
                        {
                            var iprev = Indent(prev);
                            ta.InsertString("\n" + Spaces(iprev));
                            return(true);
                        }

                        /* if (Regex.IsMatch(curline, @"^\s*\w+\s*:=", RegexOptions.IgnoreCase)) // пока тут добавление ; после присваивания. Плохо перед else! И плохо если выражение продолжается на следующей строке! Убираем.
                         * {
                         *  if (curline.Length > 0)
                         *  {
                         *      var last = curline[curline.Length - 1];
                         *      if (!char.IsLetterOrDigit(last) && last != ']' && last != ')')
                         *          return false;
                         *  }
                         *
                         *  var curlinenew = Regex.Replace(curline, @"(\s*)(\S+)(\s*):=(\s*)([^;]+)(\s*)(;?)$", @"$1$2 := $5;", RegexOptions.IgnoreCase);
                         *  while (curlinenew.EndsWith(";;"))
                         *      curlinenew = curlinenew.Remove(curlinenew.Length - 1);
                         *  doc.Replace(seg.Offset, curline.Length, curlinenew);
                         *  ta.Caret.Column = curlinenew.Length;
                         *  return false;
                         * } */
                    }
                }
                return(false);
            }
            catch (Exception e)
            {
            }
            return(false);
        }
Exemplo n.º 41
0
        public static TestRefactoringContext Create(string content, bool expectErrors = false)
        {
            int idx = content.IndexOf("$");

            if (idx >= 0)
            {
                content = content.Substring(0, idx) + content.Substring(idx + 1);
            }
            int idx1 = content.IndexOf("<-");
            int idx2 = content.IndexOf("->");

            int selectionStart = 0;
            int selectionEnd   = 0;

            if (0 <= idx1 && idx1 < idx2)
            {
                content        = content.Substring(0, idx2) + content.Substring(idx2 + 2);
                content        = content.Substring(0, idx1) + content.Substring(idx1 + 2);
                selectionStart = idx1;
                selectionEnd   = idx2 - 2;
                idx            = selectionEnd;
            }

            var doc    = new StringBuilderDocument(content);
            var parser = new CSharpParser();
            var unit   = parser.Parse(content, "program.cs");

            if (!expectErrors)
            {
                foreach (var error in parser.Errors)
                {
                    Console.WriteLine(error.Message);
                }
                Assert.IsFalse(parser.HasErrors, "The file contains unexpected parsing errors.");
            }
            else
            {
                Assert.IsTrue(parser.HasErrors, "Expected parsing errors, but the file doesn't contain any.");
            }

            unit.Freeze();
            var unresolvedFile = unit.ToTypeSystem();

            IProjectContent pc = new CSharpProjectContent();

            pc = pc.AddOrUpdateFiles(unresolvedFile);
            pc = pc.AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore });

            var          compilation = pc.CreateCompilation();
            var          resolver    = new CSharpAstResolver(compilation, unit, unresolvedFile);
            TextLocation location    = TextLocation.Empty;

            if (idx >= 0)
            {
                location = doc.GetLocation(idx);
            }
            return(new TestRefactoringContext(doc, location, resolver)
            {
                selectionStart = selectionStart,
                selectionEnd = selectionEnd
            });
        }
Exemplo n.º 42
0
 public AspNetRenderBlock(TextLocation start) : base(start)
 {
 }
Exemplo n.º 43
0
 public AspNetServerComment(TextLocation start) : base(start)
 {
 }
Exemplo n.º 44
0
 public WhitespaceNode(string whiteSpaceText, TextLocation startLocation)
 {
     this.WhiteSpaceText = whiteSpaceText;
     this.startLocation  = startLocation;
 }
Exemplo n.º 45
0
 public AspNetDataBindingExpression(TextLocation start) : base(start)
 {
 }
        protected StringBuilder CreateWrapper(string continuation, bool appendSemicolon, string afterContinuation, string memberText, TextLocation memberLocation, ref int closingBrackets, ref int generatedLines)
        {
            var  wrapper     = new StringBuilder();
            bool wrapInClass = memberLocation != new TextLocation(1, 1);

            if (wrapInClass)
            {
                wrapper.Append("class Stub {");
                wrapper.AppendLine();
                closingBrackets++;
                generatedLines++;
            }
            wrapper.Append(memberText);
            wrapper.Append(continuation);
            AppendMissingClosingBrackets(wrapper, appendSemicolon);
            wrapper.Append(afterContinuation);
            if (closingBrackets > 0)
            {
                wrapper.Append(new string('}', closingBrackets));
            }
            return(wrapper);
        }
Exemplo n.º 47
0
 public AspNetHtmlEncodedExpression(TextLocation start) : base(start)
 {
 }
Exemplo n.º 48
0
 int GetOffset(TextBox textBox, TextLocation location)
 {
     // TextBox uses 0-based coordinates, TextLocation is 1-based
     return(textBox.GetFirstCharIndexFromLine(location.Line - 1) + location.Column - 1);
 }
Exemplo n.º 49
0
 /// <summary>
 /// Returns true, if the given coordinates are in the node.
 /// </summary>
 /// <returns>
 /// True, if location is between StartLocation and EndLocation (inclusive); otherwise, false.
 /// </returns>
 public bool IsInside(TextLocation location)
 {
     return(this.StartLocation <= location && location <= this.EndLocation);
 }
Exemplo n.º 50
0
 public BreakpointBookmark(FileName fileName, TextLocation location)
 {
     this.Location = location;
     this.FileName = fileName;
 }
 /// <summary>
 /// Creates a new instance of <see cref="TextAreaUpdate"/>
 /// </summary>
 /// <param name="type">The type.</param>
 /// <param name="startLine">The start line.</param>
 /// <param name="endLine">The end line.</param>
 public TextAreaUpdate(TextAreaUpdateType type, int startLine, int endLine)
 {
     _type     = type;
     _position = new TextLocation(startLine, endLine);
 }
Exemplo n.º 52
0
 void IRelocatable.SetStartLocation(TextLocation startLocation)
 {
     this.Location = startLocation;
 }
Exemplo n.º 53
0
 public ICSharpCode.NRefactory.CSharp.Resolver.CSharpResolver GetResolver(ICompilation compilation, TextLocation loc)
 {
     return(new ICSharpCode.NRefactory.CSharp.Resolver.CSharpResolver(GetTypeResolveContext(compilation, loc)));
 }
Exemplo n.º 54
0
        public CSharpTypeResolveContext GetTypeResolveContext(ICompilation compilation, TextLocation loc)
        {
            var rctx = new CSharpTypeResolveContext(compilation.MainAssembly);

            rctx = rctx.WithUsingScope(GetUsingScope(loc).Resolve(compilation));
            var curDef = GetInnermostTypeDefinition(loc);

            if (curDef != null)
            {
                var resolvedDef = curDef.Resolve(rctx).GetDefinition();
                if (resolvedDef == null)
                {
                    return(rctx);
                }
                rctx = rctx.WithCurrentTypeDefinition(resolvedDef);

                var curMember = resolvedDef.Members.FirstOrDefault(m => m.Region.FileName == FileName && m.Region.Begin <= loc && loc < m.BodyRegion.End);
                if (curMember != null)
                {
                    rctx = rctx.WithCurrentMember(curMember);
                }
            }

            return(rctx);
        }
Exemplo n.º 55
0
 ITypeResolveContext IParsedFile.GetTypeResolveContext(ICompilation compilation, TextLocation loc)
 {
     return(GetTypeResolveContext(compilation, loc));
 }
 /// <summary>
 /// Creates a new instance of <see cref="TextAreaUpdate"/>
 /// </summary>
 public TextAreaUpdate(TextAreaUpdateType type, int singleLine)
 {
     _type     = type;
     _position = new TextLocation(0, singleLine);
 }
Exemplo n.º 57
0
 public virtual void Select(TextLocation start, TextLocation end)
 {
     // default implementation: do nothing
     // Derived classes are supposed to set the text editor's selection
 }
Exemplo n.º 58
0
 public override System.Collections.Generic.IEnumerable <CodeAction> GetActions(MonoDevelop.Ide.Gui.Document document, TextLocation loc, CancellationToken cancellationToken)
 {
     yield return(new AnalysisCodeAction(Action, Result));
 }
Exemplo n.º 59
0
 /// <summary>
 /// Given an offset in the original document (at the start of script execution),
 /// returns the offset in the current document.
 /// </summary>
 public abstract int GetCurrentOffset(TextLocation originalDocumentLocation);
Exemplo n.º 60
0
 public IUnresolvedTypeDefinition GetTopLevelTypeDefinition(TextLocation location)
 {
     return(FindEntity(topLevelTypeDefinitions, location));
 }