List <(int Offset, int Length, ReferenceUsage Usage)> FindReferences(string docString, MSBuildReferenceKind kind, object reference) { var textDoc = new StringTextSource(docString); var xmlParser = new XmlTreeParser(new XmlRootState()); var(xdoc, _) = xmlParser.Parse(new StringReader(docString)); var doc = MSBuildTestHelpers.CreateEmptyDocument(); var parseContext = new MSBuildParserContext(new NullRuntimeInformation(), null, null, null, null, new PropertyValueCollector(false), null, null, default); var sb = new MSBuildSchemaBuilder(true, parseContext, null); sb.Run(xdoc, textDoc, doc); var functionTypeProvider = new RoslynFunctionTypeProvider(null); var results = new List <(int Offset, int Length, ReferenceUsage Usage)> (); var collector = MSBuildReferenceCollector.Create(new MSBuildResolveResult { ReferenceKind = kind, Reference = reference, }, functionTypeProvider, results.Add); collector.Run(xdoc, textDoc, doc); return(results); }
public static void Run(string fileName) { var textSource = new StringTextSource(File.ReadAllText(fileName)); using (var textReader = textSource.CreateReader()) { using (var xmlReader = new XmlTextReader(textReader)) { Run(xmlReader); } } var doc = new AXmlParser().Parse(textSource); using (var xmlReader = doc.CreateReader()) { Run(xmlReader); } var xmlDocument = new XmlDocument(); xmlDocument.Load(doc.CreateReader()); xmlDocument.Save(Path.Combine(Program.TempPath, "savedXmlDocument.xml")); var xDocument = XDocument.Load(doc.CreateReader()); xDocument.Save(Path.Combine(Program.TempPath, "savedXDocument.xml")); }
public void CanGetTextFromTextBufferTextProperty() { string expectedText = "abc"; ITextSource textBuffer = new StringTextSource(expectedText); Assert.AreEqual(expectedText, textBuffer.Text); }
public void Unread_Many() { var text = "abcd"; using (var textSource = new StringTextSource(text)) { // Arbitrarily chosen array size, but bigger than the input length char[] buffer = new char[32]; int len = textSource.Read(buffer, 0, 3); Assert.Equal(3, len); Assert.Equal('a', buffer[0]); Assert.Equal('b', buffer[1]); Assert.Equal('c', buffer[2]); Assert.Equal(default(char), buffer[3]); textSource.Unread(buffer, 0, 3); len = textSource.Read(buffer, 0, 4); Assert.Equal(4, len); Assert.Equal('a', buffer[0]); Assert.Equal('b', buffer[1]); Assert.Equal('c', buffer[2]); Assert.Equal('d', buffer[3]); } }
void RequestPopup(Xwt.Rectangle rect) { var token = popupSrc.Token; Task.Run(async delegate { try { foreach (var op in await codeAction.GetPreviewOperationsAsync(token)) { if (!(op is ApplyChangesOperation ac)) { continue; } var changedDocument = ac.ChangedSolution.GetDocument(documentContext.AnalysisDocument.Id); var changedText = await changedDocument.GetTextAsync(token); var changedTextSource = new StringTextSource(changedText.ToString()); changedTextDocument = TextEditorFactory.CreateNewDocument(changedTextSource, editor.FileName); try { var processor = new DiffProcessor(editor, changedTextDocument); return(processor.Process()); } catch (Exception e) { LoggingService.LogError("Error while getting preview list diff.", e); } } } catch (OperationCanceledException) { } return(new ProcessResult()); }).ContinueWith(t => {
public IList <FoldingRegion> GetFolds(string xml) { ITextSource textBuffer = new StringTextSource(xml); Folds = Parser.GetFolds(textBuffer); return(Folds); }
public Import ParseImport(Import import) { Token.ThrowIfCancellationRequested(); var xmlParser = new XmlTreeParser(new XmlRootState()); ITextSource textSource; XDocument doc; try { textSource = new StringTextSource(File.ReadAllText(import.Filename)); (doc, _) = xmlParser.Parse(textSource.CreateReader()); } catch (Exception ex) when(IsNotCancellation(ex)) { LoggingService.LogError("Unhandled error parsing xml document", ex); return(import); } import.Document = new MSBuildDocument(import.Filename, false); import.Document.Build(doc, this); try { import.Document.Schema = SchemaProvider.GetSchema(import.Filename, import.Sdk); } catch (Exception ex) { LoggingService.LogError($"Error loading schema for '{import.Filename}'", ex); } return(import); }
public static ITextDocument LoadDocument(string fileName, string mimeType = null) { if (fileName == null) { throw new System.ArgumentNullException("fileName"); } return(currentFactory.CreateNewDocument(StringTextSource.ReadFrom(fileName), fileName, mimeType)); }
public void SkipWordBorder3() { var strategy = SearchStrategyFactory.Create("// find", false, true, SearchMode.Normal); var text = new StringTextSource(" // findtest"); var results = strategy.FindAll(text, 0, text.TextLength).ToArray(); Assert.IsEmpty(results, "No results should be found!"); }
public void Load(string fileName) { MainEditor.Document.MimeType = IdeServices.DesktopService.GetMimeTypeForUri(fileName); MainEditor.Document.Text = StringTextSource.ReadFrom(fileName).Text; this.CreateDiff(); Show(); }
XamlContext TestContext(string xaml, int offset) { var fileName = new FileName("test.xaml"); var textSource = new StringTextSource(xaml); SetUpWithCode(fileName, textSource); return(XamlContextResolver.ResolveContext(fileName, textSource, offset)); }
/// <summary> /// Loads the content from an auto save file and removes the auto save file. /// </summary> public static ITextSource LoadAndRemoveAutoSave(string fileName) { string autoSaveFileName = GetAutoSaveFileName(fileName); var result = StringTextSource.ReadFrom(autoSaveFileName); AutoSave.RemoveAutoSaveFile(fileName); return(result); }
static MSBuildRootDocument ParseDoc(string contents, string filename = "myfile.csproj") { var runtimeInfo = new MSBuildEnvironmentRuntimeInformation(); var textSource = new StringTextSource(contents); var schemaProvider = new MSBuildSchemaProvider(); var taskBuilder = new NoopTaskMetadataBuilder(); return(MSBuildRootDocument.Parse(textSource, filename, null, schemaProvider, runtimeInfo, taskBuilder, default)); }
public void ResultAtEnd() { var strategy = SearchStrategyFactory.Create("me", false, true, SearchMode.Normal); var text = new StringTextSource("result // find me"); var results = strategy.FindAll(text, 0, text.TextLength).ToArray(); Assert.AreEqual(1, results.Length, "One result should be found!"); Assert.AreEqual("result // find ".Length, results[0].Offset); Assert.AreEqual("me".Length, results[0].Length); }
public void SimpleTest() { var strategy = SearchStrategyFactory.Create("AllTests", false, false, SearchMode.Normal); var text = new StringTextSource("name=\"FindAllTests "); var results = strategy.FindAll(text, 0, text.TextLength).ToArray(); Assert.AreEqual(1, results.Length, "One result should be found!"); Assert.AreEqual("name=\"Find".Length, results[0].Offset); Assert.AreEqual("AllTests".Length, results[0].Length); }
public void CanGetTextFromReaderReturnedFromTextBufferCreateReader() { string expectedText = "abc"; ITextSource textBuffer = new StringTextSource("abc"); StringBuilder text = new StringBuilder(); using (TextReader reader = textBuffer.CreateReader()) { Assert.AreEqual(expectedText, reader.ReadToEnd()); } }
public void FromRange(int lowerBound, int upperBound, string encoding, string s) { var enc = Encoding.GetEncoding(encoding); var sut = new ValueRangeLexerFactory(); var lexer = sut.Create(lowerBound, upperBound, enc); using (var text = new StringTextSource(s)) using (var scanner = new TextScanner(text)) { var result = lexer.Read(scanner); Assert.Equal(s, result.Element.Text); } }
public void FromRange(int lowerBound, int upperBound, string encoding, string s) { var enc = Encoding.GetEncoding(encoding); var sut = new ValueRangeLexerFactory(); var lexer = sut.Create(lowerBound, upperBound, enc); using (var text = new StringTextSource(s)) using (var scanner = new TextScanner(text)) { var result = lexer.Read(scanner); Assert.Equal(s, result.Text); } }
public void Unread_One() { var text = "abcd"; using (var textSource = new StringTextSource(text)) { var a = (char)textSource.Read(); Assert.Equal('a', a); textSource.Unread(a); a = (char)textSource.Read(); Assert.Equal('a', a); } }
internal static bool HandleSourceCodeEntity(ITreeNavigator navigator, TextEditor data) { if (IsFromAssembly(navigator)) { return(false); } var method = (IUnresolvedEntity)navigator.DataItem; var source = StringTextSource.ReadFrom(method.Region.FileName); data.Text = source.Text; data.CaretLocation = new MonoDevelop.Ide.Editor.DocumentLocation(method.Region.BeginLine, method.Region.BeginColumn); return(true); }
public void Read_One() { var text = "abcd"; using (var textSource = new StringTextSource(text)) { var a = (char)textSource.Read(); Assert.Equal('a', a); var b = (char)textSource.Read(); Assert.Equal('b', b); var c = (char)textSource.Read(); Assert.Equal('c', c); } }
public static Task <ParsedDocument> ParseFile(Project project, string fileName, CancellationToken cancellationToken = default(CancellationToken)) { StringTextSource text; try { if (!File.Exists(fileName)) { return(TaskUtil.Default <ParsedDocument>()); } text = StringTextSource.ReadFrom(fileName); } catch (Exception) { return(TaskUtil.Default <ParsedDocument>()); } return(ParseFile(project, fileName, DesktopService.GetMimeTypeForUri(fileName), text, cancellationToken)); }
protected override void ApplyDocumentAdded(DocumentInfo info, SourceText text) { var id = info.Id; MonoDevelop.Projects.Project mdProject = null; if (id.ProjectId != null) { var project = CurrentSolution.GetProject(id.ProjectId); mdProject = GetMonoProject(project); if (mdProject == null) { LoggingService.LogWarning("Couldn't find project for newly generated file {0} (Project {1}).", info.Name, info.Id.ProjectId); } } var path = DetermineFilePath(info.Id, info.Name, info.FilePath, info.Folders, mdProject?.FileName.ParentDirectory, true); string formattedText; var formatter = CodeFormatterService.GetFormatter(DesktopService.GetMimeTypeForUri(path)); if (formatter != null && mdProject != null) { formattedText = formatter.FormatText(mdProject.Policies, text.ToString()); } else { formattedText = text.ToString(); } var textSource = new StringTextSource(formattedText, text.Encoding ?? System.Text.Encoding.UTF8); try { textSource.WriteTextTo(path); } catch (Exception e) { LoggingService.LogError("Exception while saving file to " + path, e); } if (mdProject != null) { var file = new MonoDevelop.Projects.ProjectFile(path); Application.Invoke(delegate { mdProject.Files.Add(file); IdeApp.ProjectOperations.SaveAsync(mdProject); }); } }
int CreateTextEditor(string text) { int markerOffset = text.IndexOf('|'); if (markerOffset != -1) { text = text.Substring(0, markerOffset) + text.Substring(markerOffset + 1); } var textSource = new StringTextSource(text); editor = TextEditorFactory.CreateNewEditor(); editor.Text = text; editor.TextChanged += DocumentTextChanged; return(markerOffset); }
string IAssemblyBrowserNodeBuilder.GetDocumentationMarkup(ITreeNavigator navigator) { var method = (IUnresolvedMethod)navigator.DataItem; var resolved = Resolve(navigator, method); if (GetMainAssembly(navigator) == null) { return(StringTextSource.ReadFrom(method.Region.FileName).Text); } StringBuilder result = new StringBuilder(); result.Append("<big>"); result.Append(MonoDevelop.Ide.TypeSystem.Ambience.EscapeText(Ambience.ConvertSymbol(resolved))); result.Append("</big>"); result.AppendLine(); //result.Append (AmbienceService.GetDocumentationMarkup (resolved, AmbienceService.GetDocumentation (resolved), options)); return(result.ToString()); }
private static void Main(string[] args) { ShowHelp(); CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; var grammar = new CalculatorGrammar(); grammar.Initialize(); var lexer = grammar.Rule <Expression>("expression"); var parser = new CalculatorParser(); string expression = null; while (expression != "") { expression = PromptLine(); if (string.IsNullOrEmpty(expression)) { return; } using (var stringTextSource = new StringTextSource(expression)) using (var textScanner = new TextScanner(stringTextSource)) { var readResult = lexer.Read(textScanner); if (readResult != null) { var textRepresentation = readResult.Text; var parseResult = parser.ParseExpression(readResult); Console.WriteLine("{0}={1}", textRepresentation, parseResult); } else { Console.WriteLine("Invalid input detected"); Console.ForegroundColor = ConsoleColor.Red; using (var reader = new TextSourceReader(stringTextSource)) { Console.WriteLine(reader.ReadToEnd()); } Console.ForegroundColor = DefaultForegroundColor; } } } }
IEnumerable <DocumentInfo> GenerateProjections(MonoDevelop.Projects.ProjectFile f, ProjectData projectData, MonoDevelop.Projects.Project p, HashSet <DocumentId> duplicates = null) { var mimeType = DesktopService.GetMimeTypeForUri(f.FilePath); var node = TypeSystemService.GetTypeSystemParserNode(mimeType, f.BuildAction); if (node == null || !node.Parser.CanGenerateProjection(mimeType, f.BuildAction, p.SupportedLanguages)) { yield break; } var options = new ParseOptions { FileName = f.FilePath, Project = p, Content = StringTextSource.ReadFrom(f.FilePath), }; var projections = node.Parser.GenerateProjections(options); var entry = new ProjectionEntry(); entry.File = f; var list = new List <Projection> (); entry.Projections = list; foreach (var projection in projections.Result) { list.Add(projection); if (duplicates != null && !duplicates.Add(projectData.GetOrCreateDocumentId(projection.Document.FileName))) { continue; } var plainName = projection.Document.FileName.FileName; yield return(DocumentInfo.Create( projectData.GetOrCreateDocumentId(projection.Document.FileName), plainName, new [] { p.Name }.Concat(f.ProjectVirtualPath.ParentDirectory.ToString().Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)), SourceCodeKind.Regular, TextLoader.From(TextAndVersion.Create(new MonoDevelopSourceText(projection.Document), VersionStamp.Create(), projection.Document.FileName)), projection.Document.FileName, false )); } projectionList.Add(entry); }
internal static IVbpProjectSymbolCache FromProject(IVbpProject project) { VbpProjectSymbolCache impl = new VbpProjectSymbolCache(project); /* Initially iterate over each module, create its parse information, and cache it! */ List <ElementBase> files = new List <ElementBase>(); files.AddRange(project.GetOwnedProject().Modules); files.AddRange(project.GetOwnedProject().Classes); files.AddRange(project.GetOwnedProject().Forms); files.AddRange(project.GetOwnedProject().UserControls); foreach (ElementBase file in files) { string fn = file.GetAbsoluteFileName(project.GetOwnedProject()); ITextSource ts = new StringTextSource(File.ReadAllText(fn)); impl._cache[fn] = CreateParseInformation(fn, ts, project); } return(impl); }
public static void Run(string fileName) { bool includeAttributes = true; var textSource = new StringTextSource(File.ReadAllText(fileName)); using (var textReader = textSource.CreateReader()) { using (var xmlReader = new XmlTextReader(textReader)) { Run(xmlReader, includeAttributes); } } var doc = new AXmlParser().Parse(textSource); using (var xmlReader = doc.CreateReader()) { Run(xmlReader, includeAttributes); } var xmlDocument = new XmlDocument(); xmlDocument.Load(doc.CreateReader()); xmlDocument.Save(Path.Combine(Program.TempPath, "savedXmlDocument.xml")); var xDocument = XDocument.Load(doc.CreateReader()); xDocument.Save(Path.Combine(Program.TempPath, "savedXDocument.xml")); File.WriteAllText(Path.Combine(Program.TempPath, "inputDocument.xml"), textSource.Text); }
void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap) { if (length == 0 && newText.TextLength == 0) return; // trying to replace a single character in 'Normal' mode? // for single characters, 'CharacterReplace' mode is equivalent, but more performant // (we don't have to touch the anchorTree at all in 'CharacterReplace' mode) if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null) offsetChangeMap = OffsetChangeMap.Empty; ITextSource removedText; if (length == 0) { removedText = StringTextSource.Empty; } else if (length < 100) { removedText = new StringTextSource(rope.ToString(offset, length)); } else { // use a rope if the removed string is long removedText = new RopeTextSource(rope.GetRange(offset, length)); } DocumentChangeEventArgs args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap); // fire DocumentChanging event if (Changing != null) Changing(this, args); if (textChanging != null) textChanging(this, args); undoStack.Push(this, args); cachedText = null; // reset cache of complete document text fireTextChanged = true; DelayedEvents delayedEvents = new DelayedEvents(); lock (lockObject) { // create linked list of checkpoints versionProvider.AppendChange(args); // now update the textBuffer and lineTree if (offset == 0 && length == rope.Length) { // optimize replacing the whole document rope.Clear(); var newRopeTextSource = newText as RopeTextSource; if (newRopeTextSource != null) rope.InsertRange(0, newRopeTextSource.GetRope()); else rope.InsertText(0, newText.Text); lineManager.Rebuild(); } else { rope.RemoveRange(offset, length); lineManager.Remove(offset, length); #if DEBUG lineTree.CheckProperties(); #endif var newRopeTextSource = newText as RopeTextSource; if (newRopeTextSource != null) rope.InsertRange(offset, newRopeTextSource.GetRope()); else rope.InsertText(offset, newText.Text); lineManager.Insert(offset, newText); #if DEBUG lineTree.CheckProperties(); #endif } } // update text anchors if (offsetChangeMap == null) { anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents); } else { foreach (OffsetChangeMapEntry entry in offsetChangeMap) { anchorTree.HandleTextChange(entry, delayedEvents); } } lineManager.ChangeComplete(args); // raise delayed events after our data structures are consistent again delayedEvents.RaiseEvents(); // fire DocumentChanged event OnChanged(args); // [DIGITALRUNE] Use protected virtual method to raise Changed event. if (textChanged != null) textChanged(this, args); }
/// <summary> /// Loads the content from an auto save file. /// </summary> public static ITextSource LoadAutoSave(string fileName) { string autoSaveFileName = GetAutoSaveFileName(fileName); return(StringTextSource.ReadFrom(autoSaveFileName)); }
IEnumerable <DocumentInfo> CreateDocuments(ProjectData projectData, MonoDevelop.Projects.Project p, CancellationToken token, MonoDevelop.Projects.ProjectFile[] sourceFiles) { var duplicates = new HashSet <DocumentId> (); // use given source files instead of project.Files because there may be additional files added by msbuild targets foreach (var f in sourceFiles) { if (token.IsCancellationRequested) { yield break; } if (f.Subtype == MonoDevelop.Projects.Subtype.Directory) { continue; } if (TypeSystemParserNode.IsCompileBuildAction(f.BuildAction)) { if (!duplicates.Add(projectData.GetOrCreateDocumentId(f.Name))) { continue; } yield return(CreateDocumentInfo(solutionData, p.Name, projectData, f)); continue; } var mimeType = DesktopService.GetMimeTypeForUri(f.FilePath); var node = TypeSystemService.GetTypeSystemParserNode(mimeType, f.BuildAction); if (node == null || !node.Parser.CanGenerateProjection(mimeType, f.BuildAction, p.SupportedLanguages)) { continue; } var options = new ParseOptions { FileName = f.FilePath, Project = p, Content = StringTextSource.ReadFrom(f.FilePath), }; var projections = node.Parser.GenerateProjections(options); var entry = new ProjectionEntry(); entry.File = f; var list = new List <Projection> (); entry.Projections = list; foreach (var projection in projections.Result) { list.Add(projection); if (!duplicates.Add(projectData.GetOrCreateDocumentId(projection.Document.FileName))) { continue; } var plainName = projection.Document.FileName.FileName; yield return(DocumentInfo.Create( projectData.GetOrCreateDocumentId(projection.Document.FileName), plainName, new [] { p.Name }.Concat(f.ProjectVirtualPath.ParentDirectory.ToString().Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)), SourceCodeKind.Regular, TextLoader.From(TextAndVersion.Create(new MonoDevelopSourceText(projection.Document), VersionStamp.Create(), projection.Document.FileName)), projection.Document.FileName, false )); } projectionList.Add(entry); } }