public override void SetReference(IDocument document)
		{
			if (diagram != null)
			{
				diagram.SelectionChanged -= new EventHandler(diagram_SelectionChanged);
			}

			if (document == null)
			{
				diagram = null;
			}
			else
			{
                // TODO do this in a sane way
                diagram = document as ClassDiagram;
			    if (diagram == null)
			    {
			        throw new Exception("This is not a class diagram");
			    }
				diagram.SelectionChanged += new EventHandler(diagram_SelectionChanged);

				mnuNewStructure.Visible = ((ClassDiagram)diagram).Language.SupportsStructures;
				mnuNewDelegate.Visible = ((ClassDiagram)diagram).Language.SupportsDelegates;
				toolNewStructure.Visible = ((ClassDiagram)diagram).Language.SupportsStructures;
				toolNewDelegate.Visible = ((ClassDiagram)diagram).Language.SupportsDelegates;
				toolDelete.Enabled = diagram.HasSelectedElement;
			}
		}
            public override ICodeIssueComputer CheckInlineMethodCondition(IDocument before, IDocument after, 
                IInlineMethodRefactoring refactoring)
            {
                // Get the out going symbols before the method is inlined.
                var writtenSymbolsBeforeInline = ConditionCheckersUtils.GetFlowOutData(ConditionCheckersUtils.GetStatementEnclosingNode
                    (refactoring.InlinedMethodInvocation), before);

                // Get the out going symbols after the method is inlined.
                var writtenSymbolsAfterInline = ConditionCheckersUtils.GetFlowOutData(refactoring.InlinedStatementsInMethodAfter, after);

                // Calculate the symbols that are added by inlining method.
                var addedSymbols = ConditionCheckersUtils.GetSymbolListExceptByName(writtenSymbolsAfterInline,
                    writtenSymbolsBeforeInline);

                // Calculate the symbols that are removed by inlining method.
                var missingSymbols = ConditionCheckersUtils.GetSymbolListExceptByName(writtenSymbolsBeforeInline,
                    writtenSymbolsAfterInline);

                // Remove 'this' symbol, it is trivial to include.
                addedSymbols = ConditionCheckersUtils.RemoveThisSymbol(addedSymbols);
                missingSymbols = ConditionCheckersUtils.RemoveThisSymbol(missingSymbols);

                // If found any missing and additional symbols, return a code issue computer.
                if(addedSymbols.Any() || missingSymbols.Any())
                {
                    logger.Info("Additional changed symbols: " + StringUtil.ConcatenateAll(",", addedSymbols.Select(s => s.Name)));
                    logger.Info("Missing changed symbols: " + StringUtil.ConcatenateAll(",", missingSymbols.Select(s => s.Name)));
                    return new ModifiedFlowOutData(refactoring.CallerMethodAfter, refactoring.InlinedMethod, refactoring.InlinedMethodInvocation,
                        refactoring.InlinedStatementsInMethodAfter, addedSymbols, missingSymbols);
                }
                return new NullCodeIssueComputer();
            }
        public CurrentFileMembersAsTreeResponse
            ( IEnumerable<IUnresolvedTypeDefinition> types
            , IDocument document) {

            this.TopLevelTypeDefinitions = types
                .Select(tld => Node.AsTree(tld, document));
        }
        public BracketSearchResult SearchBracket(IDocument document, int offset)
        {
            if (offset > 0)
            {
                char c = document.GetCharAt(offset - 1);
                int index = OpeningBrackets.IndexOf(c);
                int otherOffset = -1;
                if (index > -1)
                    otherOffset = SearchBracketForward(document, offset, OpeningBrackets[index], ClosingBrackets[index]);

                index = ClosingBrackets.IndexOf(c);
                if (index > -1)
                    otherOffset = SearchBracketBackward(document, offset - 2, OpeningBrackets[index], ClosingBrackets[index]);

                if (otherOffset > -1)
                {
                    var result = new BracketSearchResult(Math.Min(offset - 1, otherOffset), 1,
                                                         Math.Max(offset - 1, otherOffset), 1);
                    SearchDefinition(document, result);
                    return result;
                }
            }

            return null;
        }
		public static void ManageUsings(Gui.IProgressMonitor progressMonitor, string fileName, IDocument document, bool sort, bool removedUnused)
		{
			ParseInformation info = ParserService.ParseFile(fileName, document.TextContent);
			if (info == null) return;
			ICompilationUnit cu = info.MostRecentCompilationUnit;
			
			List<IUsing> newUsings = new List<IUsing>(cu.UsingScope.Usings);
			if (sort) {
				newUsings.Sort(CompareUsings);
			}
			
			if (removedUnused) {
				IList<IUsing> decl = cu.ProjectContent.Language.RefactoringProvider.FindUnusedUsingDeclarations(Gui.DomProgressMonitor.Wrap(progressMonitor), fileName, document.TextContent, cu);
				if (decl != null && decl.Count > 0) {
					foreach (IUsing u in decl) {
						string ns = null;
						for (int i = 0; i < u.Usings.Count; i++) {
							ns = u.Usings[i];
							if (ns == "System") break;
						}
						if (ns != "System") { // never remove "using System;"
							newUsings.Remove(u);
						}
					}
				}
			}
			
			// put empty line after last System namespace
			if (sort) {
				PutEmptyLineAfterLastSystemNamespace(newUsings);
			}
			
			cu.ProjectContent.Language.CodeGenerator.ReplaceUsings(new TextEditorDocument(document), cu.UsingScope.Usings, newUsings);
		}
Beispiel #6
0
		/// <summary>
		/// Creates a new instance off <see cref="DocumentEventArgs"/>
		/// </summary>
		public DocumentEventArgs(IDocument document, int offset, int length, string text)
		{
			this.document = document;
			this.offset	 = offset;
			this.length	 = length;
			this.text		 = text;
		}
        private static IDocument PrepareCompletionDocument(IDocument document, ref int offset, string usings = null, string variables = null)
        {
            if (String.IsNullOrEmpty(document.FileName))
                return document;

            //if the code is just a script it it will contain no namestpace, class and method structure and so the code completion will not work properly
            // for it to work we have to suround the code with the appropriate code structure
            //we only process the file if its a .csx file
            var fileExtension = Path.GetExtension(document.FileName);
            var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(document.FileName);
            if (String.IsNullOrEmpty(fileExtension) || String.IsNullOrEmpty(fileNameWithoutExtension))
                return document;

            if (fileExtension.ToLower() == ".csx")
            {
                string classname = replaceRegex.Replace(fileNameWithoutExtension, "");
                classname = classname.TrimStart('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');

                string header = String.Empty;
                header += (usings ?? "") + Environment.NewLine;
                header += "public static class " + classname + " {" + Environment.NewLine;
                header += "public static void Main() {" + Environment.NewLine;
                header += (variables ?? "") + Environment.NewLine;

                string footer = "}" + Environment.NewLine + "}" + Environment.NewLine;

                string code = header + document.Text + Environment.NewLine + footer;

                offset += header.Length;

                return new ReadOnlyDocument(new StringTextSource(code), document.FileName);
            }
            return document;
        }
		public void Initialize(IDocument document)
		{
			if (this.document == null) {
				this.document = document;
				this.textDocument = (TextDocument)document.GetService(typeof(TextDocument));
				this.changeList = new CompressingTreeList<LineChangeInfo>((x, y) => x.Equals(y));
			}
			
			var fileName = ((ITextEditor)document.GetService(typeof(ITextEditor))).FileName;
			
			InitializeBaseDocument();
			if (watcher != null)
				watcher.Dispose();
			
			if (usedProvider != null)
				watcher = usedProvider.WatchBaseVersionChanges(fileName, HandleBaseVersionChanges);
			
			SetupInitialFileState(fileName != currentFileName);
			currentFileName = fileName;
			
			if (!this.textDocument.LineTrackers.Contains(this)) {
				this.textDocument.LineTrackers.Add(this);
				this.textDocument.UndoStack.PropertyChanged += UndoStackPropertyChanged;
			}
		}
		public void Init()
		{
			originalXml = 
				"<root>\r\n" +
				"    <child>\r\n" +
				"    </child>\r\n" +
				"</root>";
			
			textEditor = new MockTextEditor();
			textEditor.OptionsConvertTabsToSpaces = true;
			textEditor.OptionsIndentationSize = 4;
			textEditor.OptionsIndentationString = " ";
			
			textEditor.Document.Text = originalXml;
					
			// Insert new xml as child element of <child>.
			// Insert position is just before the start of </root> end element.
			WixDocumentEditor editor = new WixDocumentEditor(textEditor);
			
			string xmlToInsert = 
				"<new-child>\r\n" +
				"</new-child>\r\n";
			
			int line = 3;
			int column = 5;
			editor.InsertIndented(line, column, xmlToInsert);
			
			document = textEditor.Document;
		}
        public CodeRefactoring GetRefactoring(IDocument document, TextSpan textSpan, CancellationToken cancellationToken)
        {
            var tree = (SyntaxTree)document.GetSyntaxTree(cancellationToken);
            var token = tree.GetRoot().FindToken(textSpan.Start);

            if (token.Parent is ClassDeclarationSyntax || token.Parent is StructDeclarationSyntax) {
                var t = (TypeDeclarationSyntax)token.Parent;
                if (!CanInferNonTrivialConstructor(t)) return null;
                return new CodeRefactoring(new[] { new ReadyCodeAction("Infer Non-Trivial Constructor", document, t, () => {
                    var c = TryInferNonTrivialConstructor(t, document.TryGetSemanticModel());
                    var i = 0;
                    var ms = t.Members.Insert(i, new[] {c}).List();
                    return t.With(members: ms);
                })});
            }

            if (token.Parent is MemberDeclarationSyntax && (token.Parent.Parent is ClassDeclarationSyntax || token.Parent.Parent is StructDeclarationSyntax)) {
                var m = (MemberDeclarationSyntax)token.Parent;
                var t = (TypeDeclarationSyntax)m.Parent;
                if (!CanInferNonTrivialConstructor(t)) return null;
                return new CodeRefactoring(new[] { new ReadyCodeAction("Infer Non-Trivial Constructor Here", document, t, () => {
                    var c = TryInferNonTrivialConstructor(t, document.TryGetSemanticModel());
                    var i = t.Members.IndexOf(m);
                    var ms = t.Members.Insert(i, new[] {c}).List();
                    return t.With(members: ms);
                })});
            }

            return null;
        }
Beispiel #11
0
		static Selection TryExtendSelectionToComments(IDocument document, Selection selection, IList<ISpecial> commentsBlankLines)
		{
			var extendedToComments = ExtendSelectionToComments(document, selection, commentsBlankLines);
			if (extendedToComments != null)
				return extendedToComments;
			return selection;
		}
Beispiel #12
0
		public BracketHighlight GetHighlight(IDocument document, int offset)
		{
			int searchOffset;
			if (document.TextEditorProperties.BracketMatchingStyle == BracketMatchingStyle.After) {
				searchOffset = offset;
			} else {
				searchOffset = offset + 1;
			}
			char word = document.GetCharAt(Math.Max(0, Math.Min(document.TextLength - 1, searchOffset)));
			
			TextLocation endP = document.OffsetToPosition(searchOffset);
			if (word == opentag) {
				if (searchOffset < document.TextLength) {
					int bracketOffset = TextUtilities.SearchBracketForward(document, searchOffset + 1, opentag, closingtag);
					if (bracketOffset >= 0) {
						TextLocation p = document.OffsetToPosition(bracketOffset);
						return new BracketHighlight(p, endP);
					}
				}
			} else if (word == closingtag) {
				if (searchOffset > 0) {
					int bracketOffset = TextUtilities.SearchBracketBackward(document, searchOffset - 1, opentag, closingtag);
					if (bracketOffset >= 0) {
						TextLocation p = document.OffsetToPosition(bracketOffset);
						return new BracketHighlight(p, endP);
					}
				}
			}
			return null;
		}
		static int SearchBracketBackward(IDocument document, int offset, char openBracket, char closingBracket)
		{
			bool inString  = false;
			char ch;
			int brackets = -1;
			for (int i = offset; i > 0; --i) {
				ch = document.GetCharAt(i);
				if (ch == openBracket && !inString) {
					++brackets;
					if (brackets == 0) return i;
				} else if (ch == closingBracket && !inString) {
					--brackets;
				} else if (ch == '"') {
					inString = !inString;
				} else if (ch == '\n') {
					int lineStart = ScanLineStart(document, i);
					if (lineStart >= 0) { // line could have a comment
						inString = false;
						for (int j = lineStart; j < i; ++j) {
							ch = document.GetCharAt(j);
							if (ch == '"') inString = !inString;
							if (ch == '\'' && !inString) {
								// comment found!
								// Skip searching in the comment:
								i = j;
								break;
							}
						}
					}
					inString = false;
				}
			}
			return -1;
		}
Beispiel #14
0
 public RenderInfo Render(IDocument document)
 {
     return new RenderInfo {
         PartialViewName = "Body",
         Model = document.Body
     };
 }
		public void Initialize(IDocument document)
		{
			if (changeList != null && changeList.Any())
				return;
			
			this.document = document;
			this.textDocument = (TextDocument)document.GetService(typeof(TextDocument));
			this.changeList = new CompressingTreeList<LineChangeInfo>((x, y) => x.Equals(y));
			
			Stream baseFileStream = GetBaseVersion();
			
			// TODO : update baseDocument on VCS actions
			if (baseFileStream != null) {
				// ReadAll() is taking care of closing the stream
				baseDocument = DocumentUtilitites.LoadReadOnlyDocumentFromBuffer(new StringTextBuffer(ReadAll(baseFileStream)));
			} else {
				if (baseDocument == null) {
					// if the file is not under subversion, the document is the opened document
					var doc = new TextDocument(textDocument.Text);
					baseDocument = new AvalonEditDocumentAdapter(doc, null);
				}
			}
			
			SetupInitialFileState(false);
			
			this.textDocument.LineTrackers.Add(this);
			this.textDocument.UndoStack.PropertyChanged += UndoStackPropertyChanged;
		}
        /// <remarks>
        /// Calculates the fold level of a specific line.
        /// </remarks>
        public List<FoldMarker> GenerateFoldMarkers(IDocument document, string fileName, object parseInfo)
        {
            var parseInformation = parseInfo as DmModelDB;
            if (parseInformation == null || parseInformation.Models == null || parseInformation.Models.Count == 0)
            {
                return null;
            }

            List<FoldMarker> foldMarkers = new List<FoldMarker>();

            foreach (var model in parseInformation.Models.Values)
            {

                var startLine = model.TokenPair.BeginToken.Line -1;
                var startColumn = model.TokenPair.BeginToken.CharPositionInLine;
                var endLine = model.TokenPair.EndToken.Line -1;
                var endColumn = model.TokenPair.EndToken.CharPositionInLine + 1;

                var fold = new FoldMarker(document, startLine, startColumn, endLine, endColumn, FoldType.Unspecified, "class " + model.Name);
                foldMarkers.Add(fold);
            }

            //if (parseInformation.BestCompilationUnit != parseInformation.MostRecentCompilationUnit)
            //{
            //    List<FoldMarker> oldFoldMarkers = GetFoldMarkers(document, parseInformation.BestCompilationUnit);
            //    int lastLine = (foldMarkers.Count == 0) ? 0 : foldMarkers[foldMarkers.Count - 1].EndLine;
            //    int totalNumberOfLines = document.TotalNumberOfLines;
            //    foreach (FoldMarker marker in oldFoldMarkers)
            //    {
            //        if (marker.StartLine > lastLine && marker.EndLine < totalNumberOfLines)
            //            foldMarkers.Add(marker);
            //    }
            //}
            return foldMarkers;
        }
            protected override ICodeIssueComputer CheckCondition(IDocument before, IDocument after,
                                                                 IManualExtractMethodRefactoring input)
            {
                // Calculate the outflow data
                IEnumerable<ISymbol> flowOuts;
                if (input.ExtractedStatements != null)
                    flowOuts = GetFlowOutData(input.ExtractedStatements, before);
                else
                    flowOuts = GetFlowOutData(input.ExtractedExpression, before);

                // Get the returning data of the return statements.
                var delaration = input.ExtractedMethodDeclaration;
                var methodAnalyzer = AnalyzerFactory.GetMethodDeclarationAnalyzer();
                methodAnalyzer.SetMethodDeclaration(delaration);

                // Get the returning data in the return statements of the extracted method, also log them.
                var returningData = GetMethodReturningData(methodAnalyzer, after);

                // Missing symbols that are in the flow out before but not in the returning data.
                // Remove this symbol.
                var missing = ConditionCheckersUtils.RemoveThisSymbol(
                    ConditionCheckersUtils.GetSymbolListExceptByName(flowOuts, returningData));

                if (missing.Any())
                {
                    return new ReturnTypeCheckingResult(input.ExtractedMethodDeclaration,
                        ConditionCheckersUtils.GetTypeNameTuples(missing));
                }
                return new NullCodeIssueComputer();
            }
        /// <summary>
        /// Selects the specified document as the currently active document.
        /// </summary>
        /// <param name="document">The document.</param>
        public void SelectDocument(IDocument document)
        {
            if (document == null) throw new ArgumentNullException("document");

            ownerUI.ShowView(views[document.Key]);
            OnDocumentSelected(document);
        }
 public void MarkTokens(IDocument document, List<LineSegment> lines)
 {
     var subs = analizer.GetSubQueries(document.TextContent.Replace("\r\n","  "), document.TextLength - 1);
     baseStrategy.MarkTokens(document, lines);
     foreach (var line in lines)
     {
         foreach (var word in line.Words)
         {
             if (!string.IsNullOrEmpty(word.Word.Trim()))
             {
                 if (word.Word.StartsWith(":"))
                 {
                     word.SyntaxColor = new HighlightColor(Color.BlueViolet,Color.Yellow, true, false);
                 }
                 else
                 {
                     var visible = analizer.GetVisibleSubQueries(subs, word.Offset + line.Offset);
                     var names = analizer.GetVisibleEntityNames(visible, word.Offset + line.Offset);
                     if (names.Any(q => q.Alias.Equals(word.Word.Split('.')[0])))
                     {
                         word.SyntaxColor = new HighlightColor(Color.DarkGoldenrod, true, true);
                     }
                     else if (names.Any(q => q.EntityName.Equals(word.Word)))
                     {
                         word.SyntaxColor = new HighlightColor(Color.DarkGoldenrod, true, false);
                     }
                 }
             }
         }
     }
 }
Beispiel #20
0
        public List<ISegment> GetLinesStartingWith(IDocument document, ref int beginIndex, string[] prefixStrs, ref bool found)
        {
            var result = new List<ISegment>();

            while (beginIndex < document.TotalNumberOfLines)
            {
                var lineSegment = _segmentGetter.GetSegment(document, beginIndex);

                if (lineSegment.Length > 0
                    && DoesLineStartWith(document, lineSegment.Offset, prefixStrs))
                {
                    found = true;
                    result.Add(lineSegment);
                    beginIndex++;
                }
                else
                {
                    if (found)
                        break;
                    else
                        beginIndex++;
                }
            }

            return result;
        }
		internal static bool SelectionIsReadOnly(IDocument document, ISelection sel)
		{
			if (document.TextEditorProperties.SupportReadOnlySegments)
				return document.MarkerStrategy.GetMarkers(sel.Offset, sel.Length).Exists(m=>m.IsReadOnly);
			else
				return false;
		}
 protected override async Task ProcessResponseAsync(IResponse response)
 {
     var context = new BrowsingContext(_parentDocument.Context, Sandboxes.None);
     var options = new CreateDocumentOptions(response, _configuration, _parentDocument);
     var factory = _configuration.GetFactory<IDocumentFactory>();
     ChildDocument = await factory.CreateAsync(context, options, CancellationToken.None).ConfigureAwait(false);
 }
Beispiel #23
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Row"/> class.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <param name="node">The node.</param>
        public Row(IDocument document, XmlNode node)
        {
            this.Document					= document;
            this.Node						= node;

            this.InitStandards();
        }
 public FixSpellingCodeAction(IDocument document, CommonSyntaxNode syntaxNode, string oldIdentifier, string newIdentifier)
 {
     this.Document = document;
     this.Node = syntaxNode;
     this.OldIdentifier = oldIdentifier;
     this.NewIdentifier = newIdentifier;
 }
        public IEnumerable<SyntaxClassification> ClassifyNode(IDocument document, CommonSyntaxNode syntax, CancellationToken cancellationToken)
        {
            // If this node is a field declaration, return syntax classifications for the
            // identifier token of each field name.
            //
            // For example, "x" and "y" would be classified in the following code:
            // 
            // class C
            // {
            //     int x, y;
            // }
            if (syntax is FieldDeclarationSyntax)
            {
                var field = (FieldDeclarationSyntax)syntax;

                return from v in field.Declaration.Variables
                       select new SyntaxClassification(v.Identifier.Span, fieldClassification);
            }

            // If this node is an identifier, use the binding API to retrieve its symbol and return a 
            // syntax classification for the node if that symbol is a field.
            if (syntax is IdentifierNameSyntax)
            {
                var semanticModel = document.GetSemanticModel(cancellationToken);
                var symbol = semanticModel.GetSemanticInfo(syntax).Symbol;

                if (symbol != null && symbol.Kind == CommonSymbolKind.Field)
                {
                    return new[] { new SyntaxClassification(syntax.Span, fieldClassification) };
                }
            }

            return null;
        }
Beispiel #26
0
		/// <summary>
		/// Creates a HTML fragment from a part of a document.
		/// </summary>
		/// <param name="document">The document to create HTML from.</param>
		/// <param name="highlighter">The highlighter used to highlight the document. <c>null</c> is valid and will create HTML without any highlighting.</param>
		/// <param name="segment">The part of the document to create HTML for. You can pass <c>null</c> to create HTML for the whole document.</param>
		/// <param name="options">The options for the HTML creation.</param>
		/// <returns>HTML code for the document part.</returns>
		public static string CreateHtmlFragment(IDocument document, IHighlighter highlighter, ISegment segment, HtmlOptions options)
		{
			if (document == null)
				throw new ArgumentNullException("document");
			if (options == null)
				throw new ArgumentNullException("options");
			if (highlighter != null && highlighter.Document != document)
				throw new ArgumentException("Highlighter does not belong to the specified document.");
			if (segment == null)
				segment = new SimpleSegment(0, document.TextLength);
			
			StringBuilder html = new StringBuilder();
			int segmentEndOffset = segment.EndOffset;
			IDocumentLine line = document.GetLineByOffset(segment.Offset);
			while (line != null && line.Offset < segmentEndOffset) {
				HighlightedLine highlightedLine;
				if (highlighter != null)
					highlightedLine = highlighter.HighlightLine(line.LineNumber);
				else
					highlightedLine = new HighlightedLine(document, line);
				SimpleSegment s = SimpleSegment.GetOverlap(segment, line);
				if (html.Length > 0)
					html.AppendLine("<br>");
				html.Append(highlightedLine.ToHtml(s.Offset, s.EndOffset, options));
				line = line.NextLine;
			}
			return html.ToString();
		}
Beispiel #27
0
		/// <exception cref="ArgumentNullException">
		/// <paramref name="document"/> is null.
		/// </exception>
		public static void Paste(IDocument document)
		{
			if (document == null)
				throw new ArgumentNullException("document");

			item.Paste(document);
		}
Beispiel #28
0
        /// <summary>
        /// Constructs and initializes editor.
        /// </summary>        
        /// <param name="document">Reference to document object.</param>
        public TableEditor(IDocument document)
            : base(document)
        {
            if (!(document is TableDocument))
                throw new ArgumentException(
                    Resources.Error_UnsupportedDocument,
                    "document");

            InitializeComponent();

            // Set columns grid databindings
            InitializeColumnsGridDatabindings();

            // Change advanced columns grid properties
            AdjustColumnsGridStyle();

            // Initialize column details tab
            InitColumnDetails();

            // Initialize foreign keys tab
            foreignKeysEdit.Document = Document;

            // Initialize indexes tab
            indexesEdit.Document = Document;
        }
		public void SetUp()
		{
			document = new DocumentFactory().CreateDocument();
			document.TextContent = "0123456789";
			marker = new TextMarker(3, 3, TextMarkerType.Underlined);
			document.MarkerStrategy.AddMarker(marker);
		}
		/// <summary>
		/// Removes all CodeCoverageMarkers from the marker strategy.
		/// </summary>
		public void RemoveMarkers(IDocument document)
		{
			ITextMarkerService markerService = document.GetService(typeof(ITextMarkerService)) as ITextMarkerService;
			if (markerService != null) {
				markerService.RemoveAll(IsCodeCoverageTextMarker);
			}
		}
 public HighlightIdentifiersStageProcess([NotNull] IFSharpFile fsFile, [NotNull] IDaemonProcess process)
     : base(process)
 {
     myFsFile   = fsFile;
     myDocument = process.Document;
 }
Beispiel #32
0
 /// <summary>
 /// Returns <see cref="IDocument"/> with default values.
 /// </summary>
 /// <param name="data">The data.</param>
 /// <returns></returns>
 public static IDocument WithDefaults(this IDocument data)
 {
     data.SetDefaults();
     return(data);
 }
Beispiel #33
0
 /// <summary>
 /// Converts the <see cref="IDocument"/> into a menu display item model.
 /// </summary>
 /// <param name="data">The document.</param>
 public static MenuDisplayItemModel ToMenuDisplayItemModel(this IDocument data)
 {
     return(data.ToMenuDisplayItemModel(group: null));
 }
Beispiel #34
0
 /// <summary>
 /// Converts the <see cref="IDocument"/> into human-readable display text.
 /// </summary>
 /// <param name="data">The data.</param>
 public static string ToDisplayText(this IDocument data)
 {
     return(data.ToDisplayText(showIdOnly: false));
 }
 protected override async Task Use(Uri url, IDocument document, CancellationToken cancel)
 {
     await Task.Yield();
 }
Beispiel #36
0
 public override void Addon(IDocument frm, NameSpace nameSpace)
 {
     throw new NotImplementedException();
 }
 public DockContentAnalysisCylinderPallet(IDocument document, AnalysisCylinderPallet analysis)
     : base(document, analysis)
 {
     InitializeComponent();
 }
 public CodeCompletionResult GetCompletions(IDocument document, int offset)
 {
     return(GetCompletions(document, offset, false));
 }
 public virtual void DrawThumbnail(IDocument doc, IGraphics g, SizeF size, Theme theme)
 {
     g.SetColor(GetThumbnailBackgroundColor(theme));
     g.FillRect(new RectangleF(PointF.Empty, size));
 }
        public CodeCompletionResult GetCompletions(IDocument document, int offset, bool controlSpace, string usings, string variables, string @namespace)
        {
            var result = new CodeCompletionResult();

            if (String.IsNullOrEmpty(document.FileName))
            {
                return(result);
            }

            var completionContext = new CSharpCompletionContext(document, offset, projectContent, usings, variables, @namespace);

            var completionFactory = new CSharpCompletionDataFactory(completionContext.TypeResolveContextAtCaret, completionContext);
            var cce = new CSharpCompletionEngine(
                completionContext.Document,
                completionContext.CompletionContextProvider,
                completionFactory,
                completionContext.ProjectContent,
                completionContext.TypeResolveContextAtCaret
                );

            cce.EolMarker        = Environment.NewLine;
            cce.FormattingPolicy = FormattingOptionsFactory.CreateSharpDevelop();


            var completionChar = completionContext.Document.GetCharAt(completionContext.Offset - 1);
            int startPos, triggerWordLength;
            IEnumerable <ICSharpCode.NRefactory.Completion.ICompletionData> completionData;

            if (controlSpace)
            {
                if (!cce.TryGetCompletionWord(completionContext.Offset, out startPos, out triggerWordLength))
                {
                    startPos          = completionContext.Offset;
                    triggerWordLength = 0;
                }
                completionData = cce.GetCompletionData(startPos, true);
                //this outputs tons of available entities
                //if (triggerWordLength == 0)
                //    completionData = completionData.Concat(cce.GetImportCompletionData(startPos));
            }
            else
            {
                startPos = completionContext.Offset;

                if (char.IsLetterOrDigit(completionChar) || completionChar == '_')
                {
                    if (startPos > 1 && char.IsLetterOrDigit(completionContext.Document.GetCharAt(startPos - 2)))
                    {
                        return(result);
                    }
                    completionData = cce.GetCompletionData(startPos, false);
                    startPos--;
                    triggerWordLength = 1;
                }
                else
                {
                    completionData    = cce.GetCompletionData(startPos, false);
                    triggerWordLength = 0;
                }
            }

            result.TriggerWordLength = triggerWordLength;
            result.TriggerWord       = completionContext.Document.GetText(completionContext.Offset - triggerWordLength, triggerWordLength);
            Debug.Print("Trigger word: '{0}'", result.TriggerWord);

            //cast to AvalonEdit completion data and add to results
            foreach (var completion in completionData)
            {
                var cshellCompletionData = completion as ICSharpCode.CodeCompletion.DataItems.CompletionData;
                if (cshellCompletionData != null)
                {
                    cshellCompletionData.TriggerWord       = result.TriggerWord;
                    cshellCompletionData.TriggerWordLength = result.TriggerWordLength;
                    result.CompletionData.Add(cshellCompletionData);
                }
            }

            //method completions
            if (!controlSpace)
            {
                // Method Insight
                var pce = new CSharpParameterCompletionEngine(
                    completionContext.Document,
                    completionContext.CompletionContextProvider,
                    completionFactory,
                    completionContext.ProjectContent,
                    completionContext.TypeResolveContextAtCaret
                    );

                var parameterDataProvider = pce.GetParameterDataProvider(completionContext.Offset, completionChar);
                result.OverloadProvider = parameterDataProvider as IOverloadProvider;
            }

            return(result);
        }
Beispiel #41
0
 public static int GetOffset([NotNull] this IDocument document, Range.pos pos)
 {
     return(GetDocumentOffset(document, (Line)(pos.Line - 1), (Column)pos.Column));
 }
Beispiel #42
0
        public static HtmlString GetTypeLink(this IExecutionContext context, IMetadata metadata, string name, bool linkTypeArguments)
        {
            name = name ?? metadata.String(CodeAnalysisKeys.DisplayName);

            // Link nullable types to their type argument
            if (metadata.String("Name") == "Nullable")
            {
                IDocument nullableType = metadata.DocumentList(CodeAnalysisKeys.TypeArguments)?.FirstOrDefault();
                if (nullableType != null)
                {
                    return(context.GetTypeLink(nullableType, name));
                }
            }

            // If it wasn't nullable, format the name
            name = FormatName(name);

            // Link the type and type parameters seperatly for generic types
            IReadOnlyList <IDocument> typeArguments = metadata.DocumentList(CodeAnalysisKeys.TypeArguments);

            if (typeArguments != null && typeArguments.Count > 0)
            {
                // Link to the original definition of the generic type
                metadata = metadata.Document(CodeAnalysisKeys.OriginalDefinition) ?? metadata;

                if (linkTypeArguments)
                {
                    // Get the type argument positions
                    int begin     = name.IndexOf("<wbr>&lt;") + 9;
                    int openParen = name.IndexOf("<wbr>(");
                    int end       = name.LastIndexOf("&gt;<wbr>", openParen == -1 ? name.Length : openParen); // Don't look past the opening paren if there is one

                    // Remove existing type arguments and insert linked type arguments (do this first to preserve original indexes)
                    name = name
                           .Remove(begin, end - begin)
                           .Insert(begin, string.Join(", <wbr>", typeArguments.Select(x => context.GetTypeLink(x, true).Value)));

                    // Insert the link for the type
                    if (metadata.ContainsKey(Keys.WritePath))
                    {
                        name = name.Insert(begin - 9, "</a>").Insert(0, $"<a href=\"{context.GetLink(metadata.FilePath(Keys.WritePath))}\">");
                    }

                    return(new HtmlString(name));
                }
            }

            // If it's a type parameter, create an anchor link to the declaring type's original definition
            if (metadata.String("Kind") == "TypeParameter")
            {
                IDocument declaringType = metadata.Document(CodeAnalysisKeys.DeclaringType)?.Document(CodeAnalysisKeys.OriginalDefinition);
                if (declaringType != null)
                {
                    return(new HtmlString(declaringType.ContainsKey(Keys.WritePath)
                        ? $"<a href=\"{context.GetLink(declaringType.FilePath(Keys.WritePath))}#typeparam-{metadata["Name"]}\">{name}</a>"
                        : name));
                }
            }

            return(new HtmlString(metadata.ContainsKey(Keys.WritePath)
                ? $"<a href=\"{context.GetLink(metadata.FilePath(Keys.WritePath))}\">{name}</a>"
                : name));
        }
Beispiel #43
0
 public static TreeOffset GetTreeOffset([NotNull] IDocument document, Line line, Column column)
 {
     return(document.GetLineLength(line) >= column
 ? new TreeOffset(document.GetOffsetByCoords(new DocumentCoords(line, column)))
 : TreeOffset.InvalidOffset);
 }
Beispiel #44
0
 public LineManager(IDocument document, IHighlightingStrategy highlightingStrategy)
 {
     this.document             = document;
     this.highlightingStrategy = highlightingStrategy;
 }
Beispiel #45
0
 public static int GetDocumentOffset([NotNull] this IDocument document, Line line, Column column)
 {
     return(document.GetLineLength(line) >= column
 ? document.GetOffsetByCoords(new DocumentCoords(line, column))
 : document.GetLineEndOffsetNoLineBreak(line));
 }
Beispiel #46
0
 public static TreeOffset GetTreeEndOffset([NotNull] this IDocument document, Range.range range)
 {
     return(GetTreeOffset(document, range.GetEndLine(), range.GetEndColumn()));
 }
Beispiel #47
0
        /// <summary>
        /// Makes the document visible to the user</summary>
        /// <param name="document">Document to show</param>
        public void Show(IDocument document)
        {
            var viewingContext = document.Cast <ViewingContext>();

            m_controlHostService.Show(viewingContext.Control);
        }
Beispiel #48
0
 public static int GetDocumentOffset([NotNull] this IDocument document, int line, int column)
 {
     return(document.GetDocumentOffset((Line)line, (Column)column));
 }
        } // Needs to say it exists, otherwise when calling ModelDescription.ExistsAsync(Language language, int version, string tag), it will fail to load this model

        public void Process(IDocument document)
        {
            Normalize(document);
        }
Beispiel #50
0
 /// <summary>
 /// Closes the document and removes any views of it from the UI</summary>
 /// <param name="document">Document to close</param>
 public void Close(IDocument document)
 {
     m_documentRegistry.Remove(document);
 }
        /// <summary>
        /// pushes the curWord string on the word list, with the
        /// correct color.
        /// </summary>
        void PushCurWord(IDocument document, ref HighlightColor markNext, List <TextWord> words)
        {
            // Svante Lidman : Need to look through the next prev logic.
            if (currentLength > 0)
            {
                if (words.Count > 0 && activeRuleSet != null)
                {
                    TextWord prevWord = null;
                    int      pInd     = words.Count - 1;
                    while (pInd >= 0)
                    {
                        if (!((TextWord)words[pInd]).IsWhiteSpace)
                        {
                            prevWord = (TextWord)words[pInd];
                            if (prevWord.HasDefaultColor)
                            {
                                PrevMarker marker = (PrevMarker)activeRuleSet.PrevMarkers[document, currentLine, currentOffset, currentLength];
                                if (marker != null)
                                {
                                    prevWord.SyntaxColor = marker.Color;
//									document.Caret.ValidateCaretPos();
//									document.RequestUpdate(new TextAreaUpdate(TextAreaUpdateType.SingleLine, document.GetLineNumberForOffset(document.Caret.Offset)));
                                }
                            }
                            break;
                        }
                        pInd--;
                    }
                }

                if (inSpan)
                {
                    HighlightColor c = null;
                    bool           hasDefaultColor = true;
                    if (activeSpan.Rule == null)
                    {
                        c = activeSpan.Color;
                    }
                    else
                    {
                        c = GetColor(activeRuleSet, document, currentLine, currentOffset, currentLength);
                        hasDefaultColor = false;
                    }

                    if (c == null)
                    {
                        c = activeSpan.Color;
                        if (c.Color == Color.Transparent)
                        {
                            c = this.DefaultTextColor;
                        }
                        hasDefaultColor = true;
                    }
                    words.Add(new TextWord(document, currentLine, currentOffset, currentLength, markNext != null ? markNext : c, hasDefaultColor));
                }
                else
                {
                    HighlightColor c = markNext != null ? markNext : GetColor(activeRuleSet, document, currentLine, currentOffset, currentLength);
                    if (c == null)
                    {
                        words.Add(new TextWord(document, currentLine, currentOffset, currentLength, this.DefaultTextColor, true));
                    }
                    else
                    {
                        words.Add(new TextWord(document, currentLine, currentOffset, currentLength, c, false));
                    }
                }

                if (activeRuleSet != null)
                {
                    NextMarker nextMarker = (NextMarker)activeRuleSet.NextMarkers[document, currentLine, currentOffset, currentLength];
                    if (nextMarker != null)
                    {
                        if (nextMarker.MarkMarker && words.Count > 0)
                        {
                            TextWord prevword = ((TextWord)words[words.Count - 1]);
                            prevword.SyntaxColor = nextMarker.Color;
                        }
                        markNext = nextMarker.Color;
                    }
                    else
                    {
                        markNext = null;
                    }
                }
                currentOffset += currentLength;
                currentLength  = 0;
            }
        }
 public void Normalize(IDocument document)
 {
     document.Value = document.Value.ToLowerInvariant();
 }
 protected virtual void OnParsedLine(IDocument document, LineSegment currentLine, List <TextWord> words)
 {
 }
        /// <summary>
        /// returns true, if the get the string s2 at index matches the expression expr
        /// </summary>
        static bool MatchExpr(LineSegment lineSegment, char[] expr, int index, IDocument document, bool ignoreCase)
        {
            for (int i = 0, j = 0; i < expr.Length; ++i, ++j)
            {
                switch (expr[i])
                {
                case '@':                         // "special" meaning
                    ++i;
                    if (i == expr.Length)
                    {
                        throw new HighlightingDefinitionInvalidException("Unexpected end of @ sequence, use @@ to look for a single @.");
                    }
                    switch (expr[i])
                    {
                    case 'C':                                     // match whitespace or punctuation
                        if (index + j == lineSegment.Offset || index + j >= lineSegment.Offset + lineSegment.Length)
                        {
                            // nothing (EOL or SOL)
                        }
                        else
                        {
                            char ch = document.GetCharAt(lineSegment.Offset + index + j);
                            if (!Char.IsWhiteSpace(ch) && !Char.IsPunctuation(ch))
                            {
                                return(false);
                            }
                        }
                        break;

                    case '!':                                     // don't match the following expression
                    {
                        StringBuilder whatmatch = new StringBuilder();
                        ++i;
                        while (i < expr.Length && expr[i] != '@')
                        {
                            whatmatch.Append(expr[i++]);
                        }
                        if (lineSegment.Offset + index + j + whatmatch.Length < document.TextLength)
                        {
                            int k = 0;
                            for (; k < whatmatch.Length; ++k)
                            {
                                char docChar  = ignoreCase ? Char.ToUpperInvariant(document.GetCharAt(lineSegment.Offset + index + j + k)) : document.GetCharAt(lineSegment.Offset + index + j + k);
                                char spanChar = ignoreCase ? Char.ToUpperInvariant(whatmatch[k]) : whatmatch[k];
                                if (docChar != spanChar)
                                {
                                    break;
                                }
                            }
                            if (k >= whatmatch.Length)
                            {
                                return(false);
                            }
                        }
//									--j;
                        break;
                    }

                    case '-':                                     // don't match the  expression before
                    {
                        StringBuilder whatmatch = new StringBuilder();
                        ++i;
                        while (i < expr.Length && expr[i] != '@')
                        {
                            whatmatch.Append(expr[i++]);
                        }
                        if (index - whatmatch.Length >= 0)
                        {
                            int k = 0;
                            for (; k < whatmatch.Length; ++k)
                            {
                                char docChar  = ignoreCase ? Char.ToUpperInvariant(document.GetCharAt(lineSegment.Offset + index - whatmatch.Length + k)) : document.GetCharAt(lineSegment.Offset + index - whatmatch.Length + k);
                                char spanChar = ignoreCase ? Char.ToUpperInvariant(whatmatch[k]) : whatmatch[k];
                                if (docChar != spanChar)
                                {
                                    break;
                                }
                            }
                            if (k >= whatmatch.Length)
                            {
                                return(false);
                            }
                        }
//									--j;
                        break;
                    }

                    case '@':                                     // matches @
                        if (index + j >= lineSegment.Length || '@' != document.GetCharAt(lineSegment.Offset + index + j))
                        {
                            return(false);
                        }
                        break;
                    }
                    break;

                default:
                {
                    if (index + j >= lineSegment.Length)
                    {
                        return(false);
                    }
                    char docChar  = ignoreCase ? Char.ToUpperInvariant(document.GetCharAt(lineSegment.Offset + index + j)) : document.GetCharAt(lineSegment.Offset + index + j);
                    char spanChar = ignoreCase ? Char.ToUpperInvariant(expr[i]) : expr[i];
                    if (docChar != spanChar)
                    {
                        return(false);
                    }
                    break;
                }
                }
            }
            return(true);
        }
        bool MarkTokensInLine(IDocument document, int lineNumber, ref bool spanChanged)
        {
            currentLineNumber = lineNumber;
            bool        processNextLine = false;
            LineSegment previousLine    = (lineNumber > 0 ? document.GetLineSegment(lineNumber - 1) : null);

            currentSpanStack = ((previousLine != null && previousLine.HighlightSpanStack != null) ? previousLine.HighlightSpanStack.Clone() : null);
            if (currentSpanStack != null)
            {
                while (!currentSpanStack.IsEmpty && currentSpanStack.Peek().StopEOL)
                {
                    currentSpanStack.Pop();
                }
                if (currentSpanStack.IsEmpty)
                {
                    currentSpanStack = null;
                }
            }

            currentLine = (LineSegment)document.LineSegmentCollection[lineNumber];

            if (currentLine.Length == -1)               // happens when buffer is empty !
            {
                return(false);
            }

            List <TextWord> words = ParseLine(document);

            if (currentSpanStack != null && currentSpanStack.IsEmpty)
            {
                currentSpanStack = null;
            }

            // Check if the span state has changed, if so we must re-render the next line
            // This check may seem utterly complicated but I didn't want to introduce any function calls
            // or allocations here for perf reasons.
            if (currentLine.HighlightSpanStack != currentSpanStack)
            {
                if (currentLine.HighlightSpanStack == null)
                {
                    processNextLine = false;
                    foreach (Span sp in currentSpanStack)
                    {
                        if (!sp.StopEOL)
                        {
                            spanChanged     = true;
                            processNextLine = true;
                            break;
                        }
                    }
                }
                else if (currentSpanStack == null)
                {
                    processNextLine = false;
                    foreach (Span sp in currentLine.HighlightSpanStack)
                    {
                        if (!sp.StopEOL)
                        {
                            spanChanged     = true;
                            processNextLine = true;
                            break;
                        }
                    }
                }
                else
                {
                    SpanStack.Enumerator e1 = currentSpanStack.GetEnumerator();
                    SpanStack.Enumerator e2 = currentLine.HighlightSpanStack.GetEnumerator();
                    bool done = false;
                    while (!done)
                    {
                        bool blockSpanIn1 = false;
                        while (e1.MoveNext())
                        {
                            if (!((Span)e1.Current).StopEOL)
                            {
                                blockSpanIn1 = true;
                                break;
                            }
                        }
                        bool blockSpanIn2 = false;
                        while (e2.MoveNext())
                        {
                            if (!((Span)e2.Current).StopEOL)
                            {
                                blockSpanIn2 = true;
                                break;
                            }
                        }
                        if (blockSpanIn1 || blockSpanIn2)
                        {
                            if (blockSpanIn1 && blockSpanIn2)
                            {
                                if (e1.Current != e2.Current)
                                {
                                    done            = true;
                                    processNextLine = true;
                                    spanChanged     = true;
                                }
                            }
                            else
                            {
                                spanChanged     = true;
                                done            = true;
                                processNextLine = true;
                            }
                        }
                        else
                        {
                            done            = true;
                            processNextLine = false;
                        }
                    }
                }
            }
            else
            {
                processNextLine = false;
            }

            //// Alex: remove old words
            if (currentLine.Words != null)
            {
                currentLine.Words.Clear();
            }
            currentLine.Words = words;
            currentLine.HighlightSpanStack = (currentSpanStack != null && !currentSpanStack.IsEmpty) ? currentSpanStack : null;

            return(processNextLine);
        }
 protected virtual bool OverrideSpan(string spanBegin, IDocument document, List <TextWord> words, Span span, ref int lineOffset)
 {
     return(false);
 }
Beispiel #57
0
 public FoldMarker(IDocument document, int startLine, int startColumn, int endLine, int endColumn, FoldType foldType, string foldText) : this(document, startLine, startColumn, endLine, endColumn, foldType, foldText, false)
 {
 }
        List <TextWord> ParseLine(IDocument document)
        {
            List <TextWord> words    = new List <TextWord>();
            HighlightColor  markNext = null;

            currentOffset = 0;
            currentLength = 0;
            UpdateSpanStateVariables();

            int currentLineLength = currentLine.Length;
            int currentLineOffset = currentLine.Offset;

            for (int i = 0; i < currentLineLength; ++i)
            {
                char ch = document.GetCharAt(currentLineOffset + i);
                switch (ch)
                {
                case '\n':
                case '\r':
                    PushCurWord(document, ref markNext, words);
                    ++currentOffset;
                    break;

                case ' ':
                    PushCurWord(document, ref markNext, words);
                    if (activeSpan != null && activeSpan.Color.HasBackground)
                    {
                        words.Add(new TextWord.SpaceTextWord(activeSpan.Color));
                    }
                    else
                    {
                        words.Add(TextWord.Space);
                    }
                    ++currentOffset;
                    break;

                case '\t':
                    PushCurWord(document, ref markNext, words);
                    if (activeSpan != null && activeSpan.Color.HasBackground)
                    {
                        words.Add(new TextWord.TabTextWord(activeSpan.Color));
                    }
                    else
                    {
                        words.Add(TextWord.Tab);
                    }
                    ++currentOffset;
                    break;

                default:
                {
                    // handle escape characters
                    char escapeCharacter = '\0';
                    if (activeSpan != null && activeSpan.EscapeCharacter != '\0')
                    {
                        escapeCharacter = activeSpan.EscapeCharacter;
                    }
                    else if (activeRuleSet != null)
                    {
                        escapeCharacter = activeRuleSet.EscapeCharacter;
                    }
                    if (escapeCharacter != '\0' && escapeCharacter == ch)
                    {
                        // we found the escape character
                        if (activeSpan != null && activeSpan.End != null && activeSpan.End.Length == 1 &&
                            escapeCharacter == activeSpan.End[0])
                        {
                            // the escape character is a end-doubling escape character
                            // it may count as escape only when the next character is the escape, too
                            if (i + 1 < currentLineLength)
                            {
                                if (document.GetCharAt(currentLineOffset + i + 1) == escapeCharacter)
                                {
                                    currentLength += 2;
                                    PushCurWord(document, ref markNext, words);
                                    ++i;
                                    continue;
                                }
                            }
                        }
                        else
                        {
                            // this is a normal \-style escape
                            ++currentLength;
                            if (i + 1 < currentLineLength)
                            {
                                ++currentLength;
                            }
                            PushCurWord(document, ref markNext, words);
                            ++i;
                            continue;
                        }
                    }

                    // highlight digits
                    if (!inSpan && (Char.IsDigit(ch) || (ch == '.' && i + 1 < currentLineLength && Char.IsDigit(document.GetCharAt(currentLineOffset + i + 1)))) && currentLength == 0)
                    {
                        bool ishex           = false;
                        bool isfloatingpoint = false;

                        if (ch == '0' && i + 1 < currentLineLength && Char.ToUpper(document.GetCharAt(currentLineOffset + i + 1)) == 'X')                                           // hex digits
                        {
                            const string hex = "0123456789ABCDEF";
                            ++currentLength;
                            ++i;                                             // skip 'x'
                            ++currentLength;
                            ishex = true;
                            while (i + 1 < currentLineLength && hex.IndexOf(Char.ToUpper(document.GetCharAt(currentLineOffset + i + 1))) != -1)
                            {
                                ++i;
                                ++currentLength;
                            }
                        }
                        else
                        {
                            ++currentLength;
                            while (i + 1 < currentLineLength && Char.IsDigit(document.GetCharAt(currentLineOffset + i + 1)))
                            {
                                ++i;
                                ++currentLength;
                            }
                        }
                        if (!ishex && i + 1 < currentLineLength && document.GetCharAt(currentLineOffset + i + 1) == '.')
                        {
                            isfloatingpoint = true;
                            ++i;
                            ++currentLength;
                            while (i + 1 < currentLineLength && Char.IsDigit(document.GetCharAt(currentLineOffset + i + 1)))
                            {
                                ++i;
                                ++currentLength;
                            }
                        }

                        if (i + 1 < currentLineLength && Char.ToUpper(document.GetCharAt(currentLineOffset + i + 1)) == 'E')
                        {
                            isfloatingpoint = true;
                            ++i;
                            ++currentLength;
                            if (i + 1 < currentLineLength && (document.GetCharAt(currentLineOffset + i + 1) == '+' || document.GetCharAt(currentLine.Offset + i + 1) == '-'))
                            {
                                ++i;
                                ++currentLength;
                            }
                            while (i + 1 < currentLine.Length && Char.IsDigit(document.GetCharAt(currentLineOffset + i + 1)))
                            {
                                ++i;
                                ++currentLength;
                            }
                        }

                        if (i + 1 < currentLine.Length)
                        {
                            char nextch = Char.ToUpper(document.GetCharAt(currentLineOffset + i + 1));
                            if (nextch == 'F' || nextch == 'M' || nextch == 'D')
                            {
                                isfloatingpoint = true;
                                ++i;
                                ++currentLength;
                            }
                        }

                        if (!isfloatingpoint)
                        {
                            bool isunsigned = false;
                            if (i + 1 < currentLineLength && Char.ToUpper(document.GetCharAt(currentLineOffset + i + 1)) == 'U')
                            {
                                ++i;
                                ++currentLength;
                                isunsigned = true;
                            }
                            if (i + 1 < currentLineLength && Char.ToUpper(document.GetCharAt(currentLineOffset + i + 1)) == 'L')
                            {
                                ++i;
                                ++currentLength;
                                if (!isunsigned && i + 1 < currentLineLength && Char.ToUpper(document.GetCharAt(currentLineOffset + i + 1)) == 'U')
                                {
                                    ++i;
                                    ++currentLength;
                                }
                            }
                        }

                        words.Add(new TextWord(document, currentLine, currentOffset, currentLength, DigitColor, false));
                        currentOffset += currentLength;
                        currentLength  = 0;
                        continue;
                    }

                    // Check for SPAN ENDs
                    if (inSpan)
                    {
                        if (activeSpan.End != null && activeSpan.End.Length > 0)
                        {
                            if (MatchExpr(currentLine, activeSpan.End, i, document, activeSpan.IgnoreCase))
                            {
                                PushCurWord(document, ref markNext, words);
                                string regex = GetRegString(currentLine, activeSpan.End, i, document);
                                currentLength += regex.Length;
                                words.Add(new TextWord(document, currentLine, currentOffset, currentLength, activeSpan.EndColor, false));
                                currentOffset += currentLength;
                                currentLength  = 0;
                                i             += regex.Length - 1;
                                currentSpanStack.Pop();
                                UpdateSpanStateVariables();
                                continue;
                            }
                        }
                    }

                    // check for SPAN BEGIN
                    if (activeRuleSet != null)
                    {
                        foreach (Span span in activeRuleSet.Spans)
                        {
                            if ((!span.IsBeginSingleWord || currentLength == 0) &&
                                (!span.IsBeginStartOfLine.HasValue || span.IsBeginStartOfLine.Value == (currentLength == 0 && words.TrueForAll(delegate(TextWord textWord) { return(textWord.Type != TextWordType.Word); }))) &&
                                MatchExpr(currentLine, span.Begin, i, document, activeRuleSet.IgnoreCase))
                            {
                                PushCurWord(document, ref markNext, words);
                                string regex = GetRegString(currentLine, span.Begin, i, document);

                                if (!OverrideSpan(regex, document, words, span, ref i))
                                {
                                    currentLength += regex.Length;
                                    words.Add(new TextWord(document, currentLine, currentOffset, currentLength, span.BeginColor, false));
                                    currentOffset += currentLength;
                                    currentLength  = 0;

                                    i += regex.Length - 1;
                                    if (currentSpanStack == null)
                                    {
                                        currentSpanStack = new SpanStack();
                                    }
                                    currentSpanStack.Push(span);
                                    span.IgnoreCase = activeRuleSet.IgnoreCase;

                                    UpdateSpanStateVariables();
                                }

                                goto skip;
                            }
                        }
                    }

                    // check if the char is a delimiter
                    if (activeRuleSet != null && (int)ch < 256 && activeRuleSet.Delimiters[(int)ch])
                    {
                        PushCurWord(document, ref markNext, words);
                        if (currentOffset + currentLength + 1 < currentLine.Length)
                        {
                            ++currentLength;
                            PushCurWord(document, ref markNext, words);
                            goto skip;
                        }
                    }

                    ++currentLength;
                    skip : continue;
                }
                }
            }

            PushCurWord(document, ref markNext, words);

            OnParsedLine(document, currentLine, words);

            return(words);
        }
Beispiel #59
0
 public FoldMarker(IDocument document, int startLine, int startColumn, int endLine, int endColumn, FoldType foldType)  : this(document, startLine, startColumn, endLine, endColumn, foldType, "...")
 {
 }
 public HighlightColor GetColor(IDocument document, LineSegment currentSegment, int currentOffset, int currentLength)
 {
     return(GetColor(defaultRuleSet, document, currentSegment, currentOffset, currentLength));
 }