示例#1
0
        public HtmlGoToDefinition(IVsTextView adapter, IWpfTextView textView)
            : base(adapter, textView, VSConstants.VSStd97CmdID.GotoDefn)
        {
            HtmlEditorDocument document = HtmlEditorDocument.TryFromTextView(textView);

            _tree = document == null ? null : document.HtmlEditorTree;
        }
示例#2
0
        private void Retrigger()
        {
            Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
            {
                var point = _textView.BufferGraph.MapDownToInsertionPoint(_textView.Caret.Position.BufferPosition - 1, PointTrackingMode.Positive, ts => ts.ContentType.IsOfType(HtmlContentTypeDefinition.HtmlContentType));
                if (point == null)
                {
                    return;
                }

                var document = HtmlEditorDocument.FromTextBuffer(point.Value.Snapshot.TextBuffer);

                if (document == null)
                {
                    return;
                }

                ElementNode element;
                AttributeNode attr;
                HtmlPositionType type = document.HtmlEditorTree.GetPositionElement(point.Value.Position, out element, out attr);

                if (document != null && type == HtmlPositionType.AttributeName)
                {
                    WebEssentialsPackage.ExecuteCommand("Edit.ListMembers");
                }
            }), DispatcherPriority.Background, null);
        }
示例#3
0
        public HtmlFindAllReferences(IVsTextView adapter, IWpfTextView textView)
            : base(adapter, textView, VSConstants.VSStd97CmdID.FindReferences)
        {
            HtmlEditorDocument document = HtmlEditorDocument.TryFromTextView(textView);

            _tree = document == null ? null : document.HtmlEditorTree;
        }
示例#4
0
        private bool HandleElement()
        {
            HtmlEditorDocument document = HtmlEditorDocument.TryFromTextView(_view);

            if (document == null)
            {
                return(false);
            }

            var tree = document.HtmlEditorTree;

            int position = _view.Caret.Position.BufferPosition.Position;

            ElementNode   tag  = null;
            AttributeNode attr = null;

            tree.GetPositionElement(position, out tag, out attr);

            if (tag != null && (tag.EndTag != null || tag.IsSelfClosing()))
            {
                int start = tag.Start;
                int end   = tag.End;

                Update(start, end);
                return(true);
            }

            return(false);
        }
示例#5
0
        private void Close()
        {
            if (_parseData == null)
            {
                return;
            }
            ParseData parseData = _parseData;

            lock (parseData)
            {
                _fullPath = null;
                _htmlDocument.OnDocumentClosing  -= OnClose;
                _htmlDocument.MassiveChangeEnded -= OnMassiveChangeEnded;
                _htmlDocument = null;
                ServiceManager.RemoveService <RazorCodeGenerator>(_viewBuffer);
                ServiceManager.RemoveService <IRazorCodeGenerator>(_viewBuffer);
                ServiceManager.RemoveService <IContainedCodeGenerator>(_viewBuffer);
                _parseData = null;
                _runtimeError.Close();
                _viewBuffer.Changed     -= TextBuffer_OnChanged;
                _viewBuffer.PostChanged -= TextBuffer_OnPostChanged;
                SetProvisionallyAcceptedState(false);
                _viewBuffer = null;
                if (_razorEditorParser != null)
                {
                    _razorEditorParser.DocumentParseComplete -= DocumentParseComplete;
                    _razorEditorParser.Close();
                    _razorEditorParser = null;
                }
            }
        }
示例#6
0
        public ProjectBlockCompletionContext(DjangoAnalyzer analyzer, ITextBuffer buffer)
            : base(analyzer, buffer, buffer.GetFileName())
        {
            var doc = HtmlEditorDocument.FromTextBuffer(buffer);

            if (doc == null)
            {
                return;
            }

            var artifacts = doc.HtmlEditorTree.ArtifactCollection;

            foreach (var artifact in artifacts.OfType <TemplateBlockArtifact>())
            {
                var artifactText = doc.HtmlEditorTree.ParseTree.Text.GetText(artifact.InnerRange);
                artifact.Parse(artifactText);
                if (artifact.Block != null)
                {
                    var varNames = artifact.Block.GetVariables();
                    foreach (var varName in varNames)
                    {
                        AddLoopVariable(varName);
                    }
                }
            }
        }
 public EnterFormat(IVsTextView adapter, IWpfTextView textView, IEditorFormatterProvider formatterProvider, ICompletionBroker broker)
     : base(adapter, textView, VSConstants.VSStd2KCmdID.RETURN)
 {
     _tree      = HtmlEditorDocument.FromTextView(textView).HtmlEditorTree;
     _formatter = formatterProvider.CreateRangeFormatter();
     _broker    = broker;
 }
示例#8
0
        public override IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span) {
            var spans = new List<ClassificationSpan>();

            var htmlDoc = HtmlEditorDocument.TryFromTextBuffer(span.Snapshot.TextBuffer);
            if (htmlDoc == null) {
                return spans;
            }

            if (_htmlDoc == null) {
                _htmlDoc = htmlDoc;
                _htmlDoc.HtmlEditorTree.UpdateCompleted += HtmlEditorTree_UpdateCompleted;
            } else {
                Debug.Assert(htmlDoc == _htmlDoc);
            }

            // If the tree is not up to date with respect to the current snapshot, then artifact ranges and the
            // associated parse results are also not up to date. We cannot force a refresh here because this
            // can potentially change the buffer, which is not legal for GetClassificationSpans to do, and will
            // break the editor. Queue the refresh for later, and asynchronously notify the editor that it needs
            // to re-classify once it's done.
            if (!_htmlDoc.HtmlEditorTree.IsReady) {
                Interlocked.Increment(ref _deferredClassifications);
                return spans;
            }

            var projSnapshot = _htmlDoc.PrimaryView.TextSnapshot as IProjectionSnapshot;
            if (projSnapshot == null) {
                return spans;
            }

            var primarySpans = projSnapshot.MapFromSourceSnapshot(span);
            foreach (var primarySpan in primarySpans) {
                var index = _htmlDoc.HtmlEditorTree.ArtifactCollection.GetItemContaining(primarySpan.Start);
                if (index < 0) {
                    continue;
                }

                var artifact = _htmlDoc.HtmlEditorTree.ArtifactCollection[index] as TemplateArtifact;
                if (artifact == null) {
                    continue;
                }

                var artifactStart = projSnapshot.MapToSourceSnapshot(artifact.InnerRange.Start);
                if (artifactStart.Snapshot != span.Snapshot) {
                    continue;
                }

                var artifactText = _htmlDoc.HtmlEditorTree.ParseTree.Text.GetText(artifact.InnerRange);
                artifact.Parse(artifactText);

                var classifications = artifact.GetClassifications();
                foreach (var classification in classifications) {
                    var classificationSpan = ToClassificationSpan(classification, span.Snapshot, artifactStart.Position);
                    spans.Add(classificationSpan);
                }
            }

            return spans;
        }
 public HtmlIdReferenceTagger(ITextView view, ITextBuffer sourceBuffer, HtmlEditorDocument document)
 {
     this.View         = view;
     this.SourceBuffer = sourceBuffer;
     this.View.Caret.PositionChanged += HandleCaretPositionChanged;
     this.View.LayoutChanged         += HandleViewLayoutChanged;
     this.HtmlDocument = document;
 }
示例#10
0
        public DirectiveGoToDefinition(IVsTextView adapter, IWpfTextView textView, DTE dte, INgHierarchyProvider ngHierarchyProvider)
            : base(adapter, textView, VSConstants.VSStd97CmdID.GotoDefn)
        {
            HtmlEditorDocument document = HtmlEditorDocument.TryFromTextView(textView);

            this.tree = document == null ? null : document.HtmlEditorTree;
            this.dte  = dte;
            this.ngHierarchyProvider = ngHierarchyProvider;
        }
示例#11
0
        internal void Create(HtmlEditorDocument document, IVsContainedLanguage containedLanguage, IVsTextBufferCoordinator bufferCoordinator, LanguageProjectionBuffer languageBuffer, out IVsTextViewFilter containedLanguageViewfilter)
        {
            containedLanguageViewfilter = null;
            TextViewData textViewDataForBuffer = TextViewConnectionListener.GetTextViewDataForBuffer(document.TextBuffer);

            if (textViewDataForBuffer == null || textViewDataForBuffer.LastActiveView == null)
            {
                return;
            }
            TextView = textViewDataForBuffer.LastActiveView;
            IVsTextViewIntellisenseHostProvider vsTextViewIntellisenseHostProvider = TextView.QueryInterface <IVsTextViewIntellisenseHostProvider>();

            if (vsTextViewIntellisenseHostProvider == null)
            {
                return;
            }

            Guid   gUID = typeof(IVsTextViewIntellisenseHost).GUID;
            IntPtr intPtr;

            vsTextViewIntellisenseHostProvider.CreateIntellisenseHost(bufferCoordinator, ref gUID, out intPtr);
            if (intPtr == IntPtr.Zero)
            {
                return;
            }

            IVsTextViewIntellisenseHost vsTextViewIntellisenseHost = Marshal.GetObjectForIUnknown(intPtr) as IVsTextViewIntellisenseHost;

            Marshal.Release(intPtr);
            if (vsTextViewIntellisenseHost == null)
            {
                return;
            }

            HtmlMainController htmlMainController = HtmlMainController.FromTextView(TextView);
            ICommandTarget     chainedController  = htmlMainController.ChainedController;

            if (chainedController == null)
            {
                return;
            }

            OleToCommandTargetShim oleToCommandTargetShim = chainedController as OleToCommandTargetShim;

            if (containedLanguage.GetTextViewFilter(vsTextViewIntellisenseHost, oleToCommandTargetShim.OleTarget, out containedLanguageViewfilter) != 0)
            {
                return;
            }

            IOleCommandTarget      oleTarget = containedLanguageViewfilter as IOleCommandTarget;
            OleToCommandTargetShim containedLanguageTarget = new OleToCommandTargetShim(TextView, oleTarget);

            ContainedLanguageTarget = containedLanguageTarget;

            _languageBuffer = languageBuffer;
            _languageBuffer.MappingsChanged += OnMappingsChanged;
        }
示例#12
0
 public VsLegacyContainedLanguageHost(HtmlEditorDocument vsDocument, LanguageProjectionBuffer secondaryBuffer, IVsHierarchy hierarchy)
 {
     _modernContainedLanguageHost = (ContainedLanguageHost.GetHost(vsDocument.PrimaryView, secondaryBuffer.IProjectionBuffer) as IWebContainedLanguageHost);
     _secondaryBuffer             = secondaryBuffer;
     this.hierarchy = hierarchy;
     _vsDocument    = vsDocument;
     _vsDocument.OnDocumentClosing    += OnDocumentClosing;
     secondaryBuffer.MappingsChanging += OnMappingsChanging;
     secondaryBuffer.MappingsChanged  += OnMappingsChanged;
 }
示例#13
0
        protected override bool Execute(FormattingCommandId commandId, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            HtmlEditorDocument document = HtmlEditorDocument.TryFromTextView(_view);

            if (document == null)
            {
                return(false);
            }

            var tree = document.HtmlEditorTree;

            int start = _view.Selection.Start.Position.Position;
            int end   = _view.Selection.End.Position.Position;

            ElementNode   tag  = null;
            AttributeNode attr = null;

            tree.GetPositionElement(start, out tag, out attr);

            if (tag == null)
            {
                return(false);
            }

            if (attr != null)
            {
                SelectAttribute(start, end, attr, tag);
            }
            else if (tag.EndTag != null && tag.StartTag.End == start && tag.EndTag.Start == end)
            {
                Select(tag.Start, tag.OuterRange.Length);
            }
            else if (tag.Children.Count > 1 && tag.Children[0].Start == start && tag.Children.Last().End == end)
            {
                Select(tag.InnerRange.Start, tag.InnerRange.Length);
            }
            else if (tag.EndTag != null && tag.Children.Count > 1 && tag.StartTag.Start < start && tag.EndTag.End > end)
            {
                Select(tag.Children[0].Start, tag.Children.Last().End - tag.Children[0].Start);
            }
            else if (tag.EndTag != null && tag.StartTag.Start < start && tag.EndTag.End > end)
            {
                Select(tag.InnerRange.Start, tag.InnerRange.Length);
            }
            else if (tag.IsSelfClosing() && tag.Start < start && tag.End > end)
            {
                Select(tag.Start, tag.OuterRange.Length);
            }
            else if (tag.Parent != null)
            {
                Select(tag.Parent.Start, tag.Parent.OuterRange.Length);
            }

            return(true);
        }
示例#14
0
        /// <summary>
        /// Finds a single property value at a given position in the TextBuffer.
        /// </summary>
        /// <param name="buffer">Any text buffer</param>
        /// <param name="position">The position in the buffer</param>
        /// <param name="attributeNames">One or more HTML attribute names, such as 'class', 'id', 'src' etc.</param>
        /// <returns>A single value matching the position in the text buffer</returns>
        public static string GetSinglePropertyValue(ITextBuffer buffer, int position, params string[] attributeNames)
        {
            var document = HtmlEditorDocument.FromTextBuffer(buffer);

            if (document == null)
            {
                return(null);
            }

            return(GetSinglePropertyValue(document.HtmlEditorTree, position, attributeNames));
        }
示例#15
0
        private void FormatTag(ElementNode element)
        {
            var schemas = AttributeNameCompletionProvider.GetSchemas();

            element = GetFirstBlockParent(element, schemas);

            ITextBuffer  buffer = HtmlEditorDocument.FromTextView(TextView).TextBuffer;
            SnapshotSpan span   = new SnapshotSpan(buffer.CurrentSnapshot, element.Start, element.Length);

            _formatter.FormatRange(TextView, buffer, span, true);
        }
示例#16
0
        public ITagger <T> CreateTagger <T>(ITextView textView, ITextBuffer buffer) where T : ITag
        {
            HtmlEditorDocument document = HtmlEditorDocument.TryFromTextBuffer(buffer);

            if (document == null)
            {
                return(null);
            }

            return(new RadioButtonGroupNameReferenceTagger(textView, buffer, document) as ITagger <T>);
        }
示例#17
0
        private void OnDocumentClosing(object sender, EventArgs e)
        {
            if (Closing != null)
            {
                Closing(this, new ContainedLanguageHostClosingEventArgs(this, _secondaryBuffer.IProjectionBuffer));
            }

            _secondaryBuffer.MappingsChanging -= OnMappingsChanging;
            _secondaryBuffer.MappingsChanged  -= OnMappingsChanged;
            _vsDocument.OnDocumentClosing     -= OnDocumentClosing;
            _vsDocument = null;
        }
示例#18
0
 private static void UpdateBuffer(string innerHTML, HtmlEditorDocument html, Span span)
 {
     using (WebEssentialsPackage.UndoContext("Design Mode changes"))
     {
         try
         {
             html.TextBuffer.Replace(span, innerHTML);
             WebEssentialsPackage.DTE.ActiveDocument.Save();
         }
         catch
         {
             // Do nothing
         }
     }
 }
示例#19
0
 internal static HtmlEditorDocument HtmlEditorDocumentFromTextBuffer(ITextBuffer buffer) {
     var doc = HtmlEditorDocument.FromTextBuffer(buffer);
     if (doc == null) {
         var projBuffer = buffer as IProjectionBuffer;
         if (projBuffer != null) {
             foreach (var b in projBuffer.SourceBuffers) {
                 if (b.ContentType.IsOfType(TemplateHtmlContentType.ContentTypeName) &&
                     (doc = HtmlEditorDocument.TryFromTextBuffer(b)) != null) {
                     return doc;
                 }
             }
         }
     }
     return doc;
 }
示例#20
0
        public void UpdateSource(string innerHtml, string file, int position)
        {
            WebEssentialsPackage.DTE.ItemOperations.OpenFile(file);

            Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
            {
                var view = ProjectHelpers.GetCurentTextView();
                var html = HtmlEditorDocument.TryFromTextView(view);

                if (html == null)
                {
                    return;
                }

                ElementNode element;
                AttributeNode attribute;

                view.Selection.Clear();
                html.HtmlEditorTree.GetPositionElement(position + 1, out element, out attribute);

                // HTML element
                if (element != null && element.Start == position)
                {
                    Span span   = new Span(element.InnerRange.Start, element.InnerRange.Length);
                    string text = html.TextBuffer.CurrentSnapshot.GetText(span);

                    if (text != innerHtml)
                    {
                        UpdateBuffer(innerHtml, html, span);
                    }
                }
                // ActionLink
                else if (element.Start != position)
                {
                    //@Html.ActionLink("Application name", "Index", "Home", null, new { @class = "brand" })
                    Span span = new Span(position, 100);

                    if (position + 100 < html.TextBuffer.CurrentSnapshot.Length)
                    {
                        string text = html.TextBuffer.CurrentSnapshot.GetText(span);
                        var result  = Regex.Replace(text, @"^html.actionlink\(""([^""]+)""", "Html.ActionLink(\"" + innerHtml + "\"", RegexOptions.IgnoreCase);

                        UpdateBuffer(result, html, span);
                    }
                }
            }), DispatcherPriority.ApplicationIdle, null);
        }
示例#21
0
        public void UpdateSource(string innerHtml, string file, int position)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            VsHelpers.DTE.ItemOperations.OpenFile(file);

            ThreadHelper.JoinableTaskFactory.Run(async() =>
            {
                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
                Microsoft.VisualStudio.Text.Editor.IWpfTextView view = VsHelpers.GetCurentTextView();
                HtmlEditorDocument html = HtmlEditorDocument.TryFromTextView(view);

                if (html == null)
                {
                    return;
                }

                view.Selection.Clear();
                html.HtmlEditorTree.GetPositionElement(position + 1, out ElementNode element, out AttributeNode attribute);

                // HTML element
                if (element != null && element.Start == position)
                {
                    Span span   = new Span(element.InnerRange.Start, element.InnerRange.Length);
                    string text = html.TextBuffer.CurrentSnapshot.GetText(span);

                    if (text != innerHtml)
                    {
                        UpdateBuffer(innerHtml, html, span);
                    }
                }
                // ActionLink
                else if (element.Start != position)
                {
                    //@Html.ActionLink("Application name", "Index", "Home", null, new { @class = "brand" })
                    Span span = new Span(position, 100);

                    if (position + 100 < html.TextBuffer.CurrentSnapshot.Length)
                    {
                        string text   = html.TextBuffer.CurrentSnapshot.GetText(span);
                        string result = Regex.Replace(text, @"^html.actionlink\(""([^""]+)""", "Html.ActionLink(\"" + innerHtml + "\"", RegexOptions.IgnoreCase);

                        UpdateBuffer(result, html, span);
                    }
                }
            });
        }
示例#22
0
 private static void UpdateBuffer(string innerHTML, HtmlEditorDocument html, Span span)
 {
     try
     {
         EditorExtensionsPackage.DTE.UndoContext.Open("Design Mode changes");
         html.TextBuffer.Replace(span, innerHTML);
         EditorExtensionsPackage.DTE.ActiveDocument.Save();
     }
     catch
     {
         // Do nothing
     }
     finally
     {
         EditorExtensionsPackage.DTE.UndoContext.Close();
     }
 }
示例#23
0
        public override void AugmentCompletionSession(ICompletionSession session, IList <CompletionSet> completionSets)
        {
            var doc = HtmlEditorDocument.FromTextBuffer(_buffer);

            if (doc == null)
            {
                return;
            }
            doc.HtmlEditorTree.EnsureTreeReady();

            var primarySnapshot      = doc.PrimaryView.TextSnapshot;
            var nullableTriggerPoint = session.GetTriggerPoint(primarySnapshot);

            if (!nullableTriggerPoint.HasValue)
            {
                return;
            }
            var triggerPoint = nullableTriggerPoint.Value;

            var artifacts = doc.HtmlEditorTree.ArtifactCollection;
            var index     = artifacts.GetItemContaining(triggerPoint.Position);

            if (index < 0)
            {
                return;
            }

            var artifact = artifacts[index] as TemplateArtifact;

            if (artifact == null)
            {
                return;
            }

            var artifactText = doc.HtmlEditorTree.ParseTree.Text.GetText(artifact.InnerRange);

            artifact.Parse(artifactText);

            ITrackingSpan applicableSpan;
            var           completionSet = GetCompletionSet(session.GetOptions(_analyzer._serviceProvider), _analyzer, artifact.TokenKind, artifactText, artifact.InnerRange.Start, triggerPoint, out applicableSpan);

            completionSets.Add(completionSet);
        }
示例#24
0
        private static void UpdateBuffer(string innerHTML, HtmlEditorDocument html, Span span)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            VsHelpers.DTE.UndoContext.Open("Design Mode changes");

            try
            {
                html.TextBuffer.Replace(span, innerHTML);
                VsHelpers.DTE.ActiveDocument.Save();
            }
            catch
            {
                // Do nothing
            }
            finally
            {
                VsHelpers.DTE.UndoContext.Close();
            }
        }
示例#25
0
        public void AugmentQuickInfoSession(IQuickInfoSession session, IList <object> qiContent, out ITrackingSpan applicableToSpan)
        {
            applicableToSpan = null;

            SnapshotPoint?point = session.GetTriggerPoint(session.TextView.TextBuffer.CurrentSnapshot);

            if (!point.HasValue)
            {
                return;
            }

            HtmlEditorTree tree = HtmlEditorDocument.TryFromTextView(session.TextView).HtmlEditorTree;

            if (tree == null)
            {
                return;
            }

            ElementNode   node = null;
            AttributeNode attr = null;

            tree.GetPositionElement(point.Value.Position, out node, out attr);

            if (node == null || (!node.Name.Equals("img", StringComparison.OrdinalIgnoreCase) && !node.Name.Equals("source", StringComparison.OrdinalIgnoreCase)))
            {
                return;
            }
            if (attr == null || !attr.Name.Equals("src", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            string url = ImageQuickInfo.GetFullUrl(attr.Value, session.TextView.TextBuffer);

            if (string.IsNullOrEmpty(url))
            {
                return;
            }

            applicableToSpan = session.TextView.TextBuffer.CurrentSnapshot.CreateTrackingSpan(point.Value.Position, 1, SpanTrackingMode.EdgeNegative);

            ImageQuickInfo.AddImageContent(qiContent, url);
        }
示例#26
0
        protected override IEnumerable <DjangoBlock> GetBlocks(IEnumerable <CompletionInfo> results, SnapshotPoint triggerPoint)
        {
            var doc = HtmlEditorDocument.FromTextBuffer(_buffer);

            if (doc == null)
            {
                yield break;
            }

            var artifacts = doc.HtmlEditorTree.ArtifactCollection.ItemsInRange(new TextRange(0, triggerPoint.Position));

            foreach (var artifact in artifacts.OfType <TemplateBlockArtifact>().Reverse())
            {
                var artifactText = doc.HtmlEditorTree.ParseTree.Text.GetText(artifact.InnerRange);
                artifact.Parse(artifactText);
                if (artifact.Block != null)
                {
                    yield return(artifact.Block);
                }
            }
        }
示例#27
0
 private RazorSpanClassifier(ITextBuffer diskBuffer)
 {
     try
     {
         _diskBuffer = diskBuffer;
         IClassificationTypeRegistryService value = WebEditor.ExportProvider.GetExport <IClassificationTypeRegistryService>().Value;
         string type  = HtmlClassificationTypes.MapToEditorClassification("HtmlServerCodeBlockSeparator");
         string type2 = HtmlClassificationTypes.MapToEditorClassification("HtmlComment");
         _razorDelimiterClassificationType = value.GetClassificationType(type);
         _razorCommentClassificationType   = value.GetClassificationType(type2);
         _spansToClassify             = new List <ClassificationData>();
         _document                    = ServiceManager.GetService <HtmlEditorDocument>(diskBuffer);
         _document.OnDocumentClosing += OnDocumentClosing;
         ServiceManager.AddService <RazorSpanClassifier>(this, _diskBuffer);
     }
     catch
     {
         OnDocumentClosing(null, EventArgs.Empty);
         throw;
     }
 }
示例#28
0
 private RazorSpanClassifier(ITextBuffer diskBuffer)
 {
     try
     {
         _diskBuffer = diskBuffer;
         IClassificationTypeRegistryService value = WebEditor.ExportProvider.GetExport<IClassificationTypeRegistryService>().Value;
         string type = HtmlClassificationTypes.MapToEditorClassification("HtmlServerCodeBlockSeparator");
         string type2 = HtmlClassificationTypes.MapToEditorClassification("HtmlComment");
         _razorDelimiterClassificationType = value.GetClassificationType(type);
         _razorCommentClassificationType = value.GetClassificationType(type2);
         _spansToClassify = new List<ClassificationData>();
         _document = ServiceManager.GetService<HtmlEditorDocument>(diskBuffer);
         _document.OnDocumentClosing += OnDocumentClosing;
         ServiceManager.AddService<RazorSpanClassifier>(this, _diskBuffer);
     }
     catch
     {
         OnDocumentClosing(null, EventArgs.Empty);
         throw;
     }
 }
示例#29
0
        protected override IEnumerable <DjangoBlock> GetBlocks(IEnumerable <CompletionInfo> results, SnapshotPoint triggerPoint)
        {
            var buffers = _buffer.GetContributingBuffers().Where(b => b.ContentType.IsOfType(TemplateHtmlContentType.ContentTypeName));
            var doc     = HtmlEditorDocument.FromTextBuffer(buffers.FirstOrDefault() ?? _buffer);

            if (doc == null)
            {
                yield break;
            }

            var artifacts = doc.HtmlEditorTree.ArtifactCollection.ItemsInRange(new TextRange(0, triggerPoint.Position));

            foreach (var artifact in artifacts.OfType <TemplateBlockArtifact>().Reverse())
            {
                var artifactText = doc.HtmlEditorTree.ParseTree.Text.GetText(artifact.InnerRange.Start, artifact.InnerRange.Length);
                artifact.Parse(artifactText);
                if (artifact.Block != null)
                {
                    yield return(artifact.Block);
                }
            }
        }
        internal void Create(HtmlEditorDocument document, IVsContainedLanguage containedLanguage, IVsTextBufferCoordinator bufferCoordinator, LanguageProjectionBuffer languageBuffer, out IVsTextViewFilter containedLanguageViewfilter)
        {
            containedLanguageViewfilter = null;
            TextViewData textViewDataForBuffer = TextViewConnectionListener.GetTextViewDataForBuffer(document.TextBuffer);
            if (textViewDataForBuffer == null || textViewDataForBuffer.LastActiveView == null)
                return;
            TextView = textViewDataForBuffer.LastActiveView;
            IVsTextViewIntellisenseHostProvider vsTextViewIntellisenseHostProvider = TextView.QueryInterface<IVsTextViewIntellisenseHostProvider>();
            if (vsTextViewIntellisenseHostProvider == null)
                return;

            Guid gUID = typeof(IVsTextViewIntellisenseHost).GUID;
            IntPtr intPtr;
            vsTextViewIntellisenseHostProvider.CreateIntellisenseHost(bufferCoordinator, ref gUID, out intPtr);
            if (intPtr == IntPtr.Zero)
                return;

            IVsTextViewIntellisenseHost vsTextViewIntellisenseHost = Marshal.GetObjectForIUnknown(intPtr) as IVsTextViewIntellisenseHost;
            Marshal.Release(intPtr);
            if (vsTextViewIntellisenseHost == null)
                return;

            HtmlMainController htmlMainController = HtmlMainController.FromTextView(TextView);
            ICommandTarget chainedController = htmlMainController.ChainedController;
            if (chainedController == null)
                return;

            OleToCommandTargetShim oleToCommandTargetShim = chainedController as OleToCommandTargetShim;
            if (containedLanguage.GetTextViewFilter(vsTextViewIntellisenseHost, oleToCommandTargetShim.OleTarget, out containedLanguageViewfilter) != 0)
                return;

            IOleCommandTarget oleTarget = containedLanguageViewfilter as IOleCommandTarget;
            OleToCommandTargetShim containedLanguageTarget = new OleToCommandTargetShim(TextView, oleTarget);
            ContainedLanguageTarget = containedLanguageTarget;

            _languageBuffer = languageBuffer;
            _languageBuffer.MappingsChanged += OnMappingsChanged;
        }
示例#31
0
        private void FormatTag(ElementNode element)
        {
            try
            {
                var schemas = GetSchemas();

                element = GetFirstBlockParent(element, schemas);

                HtmlEditorDocument document = HtmlEditorDocument.TryFromTextView(TextView);

                if (document == null)
                {
                    return;
                }

                ITextBuffer  buffer = document.TextBuffer;
                SnapshotSpan span   = new SnapshotSpan(buffer.CurrentSnapshot, element.Start, element.Length);

                _formatter.FormatRange(TextView, buffer, span, true);
            }
            catch
            { }
        }
示例#32
0
        protected override bool Execute(uint commandId, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            HtmlEditorDocument document = HtmlEditorDocument.FromTextView(_view);
            var tree = document.HtmlEditorTree;

            int start = _view.Selection.Start.Position.Position;
            int end   = _view.Selection.End.Position.Position;

            ElementNode   tag  = null;
            AttributeNode attr = null;

            tree.GetPositionElement(start + 1, out tag, out attr);

            if (tag == null)
            {
                return(false);
            }

            if (tag.EndTag != null && tag.StartTag.Start == start && tag.EndTag.End == end)
            {
                Select(tag.InnerRange.Start, tag.InnerRange.Length);
            }
            else if (tag.Parent != null && tag.Children.Count > 0 && (tag.Start != start || tag.Parent.Children.Last().End != end))
            {
                Select(tag.Children.First().Start, tag.Children.Last().End - tag.Children.First().Start);
            }
            else if (tag.Parent != null && tag.Parent.Children.First().Start == start && tag.Parent.Children.Last().End == end)
            {
                SelectCaretNode(tree, tag.Parent);
            }
            else if (tag.Children.Count > 0)
            {
                SelectCaretNode(tree, tag);
            }

            return(true);
        }
        public void AugmentQuickInfoSession(IQuickInfoSession session, IList <object> qiContent, out ITrackingSpan applicableToSpan)
        {
            applicableToSpan = null;

            SnapshotPoint?point = session.GetTriggerPoint(session.TextView.TextBuffer.CurrentSnapshot);

            if (!point.HasValue)
            {
                return;
            }

            HtmlEditorTree tree = HtmlEditorDocument.FromTextView(session.TextView).HtmlEditorTree;

            ElementNode   node = null;
            AttributeNode attr = null;

            tree.GetPositionElement(point.Value.Position, out node, out attr);

            if (attr == null || (attr.Name != "href" && attr.Name != "src"))
            {
                return;
            }

            string url = GetFileName(attr.Value.Trim('\'', '"').TrimStart('~'));

            if (!string.IsNullOrEmpty(url))
            {
                applicableToSpan = session.TextView.TextBuffer.CurrentSnapshot.CreateTrackingSpan(point.Value.Position, 1, SpanTrackingMode.EdgeNegative);
                var image = CreateImage(url);
                if (image != null && image.Source != null)
                {
                    qiContent.Add(image);
                    qiContent.Add(Math.Round(image.Source.Width) + "x" + Math.Round(image.Source.Height));
                }
            }
        }
示例#34
0
        public override IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span) {
            var spans = new List<ClassificationSpan>();

            var htmlDoc = HtmlEditorDocumentFromTextBuffer(span.Snapshot.TextBuffer);
            if (htmlDoc == null) {
                return spans;
            }

            if (_htmlDoc == null) {
                _htmlDoc = htmlDoc;
                _htmlDoc.HtmlEditorTree.UpdateCompleted += HtmlEditorTree_UpdateCompleted;
            } else {
                Debug.Assert(htmlDoc == _htmlDoc);
            }

            // If the tree is not up to date with respect to the current snapshot, then artifact ranges and the
            // associated parse results are also not up to date. We cannot force a refresh here because this
            // can potentially change the buffer, which is not legal for GetClassificationSpans to do, and will
            // break the editor. Queue the refresh for later, and asynchronously notify the editor that it needs
            // to re-classify once it's done.
            if (!_htmlDoc.HtmlEditorTree.IsReady) {
                Interlocked.Increment(ref _deferredClassifications);
                return spans;
            }

            // The provided span may be in a projection snapshot, so we need to
            // map back to the source snapshot to find the correct
            // classification. If projSnapshot is null, we are already in the
            // correct snapshot.
            var projSnapshot = span.Snapshot as IProjectionSnapshot;
            var sourceSnapshot = span.Snapshot;

            var sourceStartIndex = span.Start.Position;
            if (projSnapshot != null) {
                var pt = projSnapshot.MapToSourceSnapshot(sourceStartIndex);
                sourceStartIndex = pt.Position;
                sourceSnapshot = pt.Snapshot;
                if (HtmlEditorDocument.TryFromTextBuffer(sourceSnapshot.TextBuffer) != _htmlDoc) {
                    return spans;
                }
            }

            var index = _htmlDoc.HtmlEditorTree.ArtifactCollection.GetItemContaining(sourceStartIndex);
            if (index < 0) {
                return spans;
            }

            var artifact = _htmlDoc.HtmlEditorTree.ArtifactCollection[index] as TemplateArtifact;
            if (artifact == null) {
                return spans;
            }

            int artifactStart = artifact.InnerRange.Start;
            var artifactText = _htmlDoc.HtmlEditorTree.ParseTree.Text.GetText(artifact.InnerRange);
            artifact.Parse(artifactText);

            var classifications = artifact.GetClassifications();
            foreach (var classification in classifications) {
                var cls = GetClassification(classification.Classification);
                int clsStart = artifactStart + classification.Span.Start;
                int clsLen = Math.Min(sourceSnapshot.Length - clsStart, classification.Span.Length);
                var clsSpan = new SnapshotSpan(sourceSnapshot, clsStart, clsLen);
                if (projSnapshot != null) {
                    foreach (var sp in projSnapshot.MapFromSourceSnapshot(clsSpan)) {
                        spans.Add(new ClassificationSpan(new SnapshotSpan(span.Snapshot, sp), cls));
                    }
                } else {
                    spans.Add(new ClassificationSpan(clsSpan, cls));
                }
            }

            return spans;
        }
 public VsLegacyContainedLanguageHost(HtmlEditorDocument vsDocument, LanguageProjectionBuffer secondaryBuffer, IVsHierarchy hierarchy)
 {
     _modernContainedLanguageHost = (ContainedLanguageHost.GetHost(vsDocument.PrimaryView, secondaryBuffer.IProjectionBuffer) as IWebContainedLanguageHost);
     _secondaryBuffer = secondaryBuffer;
     this.hierarchy = hierarchy;
     _vsDocument = vsDocument;
     _vsDocument.OnDocumentClosing += OnDocumentClosing;
     secondaryBuffer.MappingsChanging += OnMappingsChanging;
     secondaryBuffer.MappingsChanged += OnMappingsChanged;
 }
        private void OnDocumentClosing(object sender, EventArgs e)
        {
            if (Closing != null)
            {
                Closing(this, new ContainedLanguageHostClosingEventArgs(this, _secondaryBuffer.IProjectionBuffer));
            }

            _secondaryBuffer.MappingsChanging -= OnMappingsChanging;
            _secondaryBuffer.MappingsChanged -= OnMappingsChanged;
            _vsDocument.OnDocumentClosing -= OnDocumentClosing;
            _vsDocument = null;
        }
 private static void UpdateBuffer(string innerHTML, HtmlEditorDocument html, Span span)
 {
     try
     {
         EditorExtensionsPackage.DTE.UndoContext.Open("Design Mode changes");
         html.TextBuffer.Replace(span, innerHTML);
         EditorExtensionsPackage.DTE.ActiveDocument.Save();
     }
     catch
     {
         // Do nothing
     }
     finally
     {
         EditorExtensionsPackage.DTE.UndoContext.Close();
     }
 }
示例#38
0
		private RazorCodeGenerator(Microsoft.VisualStudio.Text.ITextBuffer buffer, Version razorVersion, string physicalPath, string virtualPath)
		{
			WebEditor.CompositionService.SatisfyImportsOnce(this);
			_parseData = new ParseData();
			_viewBuffer = buffer;
			_viewBuffer.Changed += TextBuffer_OnChanged;
			_viewBuffer.PostChanged += TextBuffer_OnPostChanged;
			_htmlDocument = ServiceManager.GetService<HtmlEditorDocument>(_viewBuffer);
			_htmlDocument.OnDocumentClosing += OnClose;
            _htmlDocument.MassiveChangeEnded += OnMassiveChangeEnded;
			_fullPath = ((!string.IsNullOrEmpty(physicalPath)) ? physicalPath : "Default.cshtml");
			if (virtualPath == null)
			{
				virtualPath = "Default.cshtml";
			}
			_runtimeError = new RazorRuntimeError(_viewBuffer);
			_razorEditorParser = new ShimRazorEditorParserImpl(virtualPath, _fullPath);
			_razorEditorParser.DocumentParseComplete += DocumentParseComplete;
			ReparseFile();
			WebEditor.OnIdle += OnFirstIdle;
			ServiceManager.AddService(this, _viewBuffer);
			ServiceManager.AddService<IRazorCodeGenerator>(this, _viewBuffer);
			ServiceManager.AddService<IContainedCodeGenerator>(this, _viewBuffer);
		}
示例#39
0
		private void Close()
		{
			if (_parseData == null)
			{
				return;
			}
            ParseData parseData = _parseData;
			lock (parseData)
			{
				_fullPath = null;
				_htmlDocument.OnDocumentClosing -= OnClose;
				_htmlDocument.MassiveChangeEnded -= OnMassiveChangeEnded;
				_htmlDocument = null;
				ServiceManager.RemoveService<RazorCodeGenerator>(_viewBuffer);
				ServiceManager.RemoveService<IRazorCodeGenerator>(_viewBuffer);
				ServiceManager.RemoveService<IContainedCodeGenerator>(_viewBuffer);
				_parseData = null;
				_runtimeError.Close();
				_viewBuffer.Changed -= TextBuffer_OnChanged;
				_viewBuffer.PostChanged -= TextBuffer_OnPostChanged;
				SetProvisionallyAcceptedState(false);
				_viewBuffer = null;
				if (_razorEditorParser != null)
				{
					_razorEditorParser.DocumentParseComplete -= DocumentParseComplete;
					_razorEditorParser.Close();
					_razorEditorParser = null;
				}
			}
		}
 private static void UpdateBuffer(string innerHTML, HtmlEditorDocument html, Span span)
 {
     using (WebEssentialsPackage.UndoContext("Design Mode changes"))
     {
         try
         {
             html.TextBuffer.Replace(span, innerHTML);
             WebEssentialsPackage.DTE.ActiveDocument.Save();
         }
         catch
         {
             // Do nothing
         }
     }
 }