private static string AddMissingVendorDeclarations(StringBuilder sb, CssEditorDocument doc, ICssSchemaInstance rootSchema, out int count)
        {
            var visitor = new CssItemCollector<Declaration>(true);
            doc.Tree.StyleSheet.Accept(visitor);
            count = 0;

            var items = visitor.Items.Where(d => d.IsValid && !d.IsVendorSpecific() && d.PropertyName.Text != "filter");

            foreach (Declaration dec in items.Reverse())
            {
                ICssSchemaInstance schema = CssSchemaManager.SchemaManager.GetSchemaForItem(rootSchema, dec);
                var missingEntries = dec.GetMissingVendorSpecifics(schema);

                if (missingEntries.Any())
                {
                    var missingPrefixes = missingEntries.Select(e => e.Substring(0, e.IndexOf('-', 1) + 1));
                    string vendors = GetVendorDeclarations(missingPrefixes, dec);

                    sb.Insert(dec.Start, vendors);
                    count++;
                }
            }

            return sb.ToString();
        }
        private string AddMissingStandardDeclaration(StringBuilder sb, CssEditorDocument doc, ICssSchemaInstance rootSchema)
        {
            var visitor = new CssItemCollector<RuleBlock>(true);
            doc.Tree.StyleSheet.Accept(visitor);

            //var items = visitor.Items.Where(d => d.IsValid && d.IsVendorSpecific());
            foreach (RuleBlock rule in visitor.Items.Reverse())
            {
                HashSet<string> list = new HashSet<string>();
                foreach (Declaration dec in rule.Declarations.Where(d => d.IsValid && d.IsVendorSpecific()).Reverse())
                {
                    ICssSchemaInstance schema = CssSchemaManager.SchemaManager.GetSchemaForItem(rootSchema, dec);
                    ICssCompletionListEntry entry = VendorHelpers.GetMatchingStandardEntry(dec, schema);

                    if (entry != null && !list.Contains(entry.DisplayText) && !rule.Declarations.Any(d => d.PropertyName != null && d.PropertyName.Text == entry.DisplayText))
                    {
                        int index = dec.Text.IndexOf(":", StringComparison.Ordinal);
                        string standard = entry.DisplayText + dec.Text.Substring(index);

                        sb.Insert(dec.AfterEnd, standard);
                        list.Add(entry.DisplayText);
                    }
                }
            }

            return sb.ToString();
        }
Esempio n. 3
0
        protected override bool Execute(ExtractCommandId commandId, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            var point = TextView.GetSelection("LESS");

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

            ITextBuffer buffer = point.Value.Snapshot.TextBuffer;
            var         doc    = CssEditorDocument.FromTextBuffer(buffer);
            ParseItem   item   = doc.StyleSheet.ItemBeforePosition(point.Value);
            ParseItem   rule   = FindParent(item);

            string text = item.Text;
            string name = Microsoft.VisualBasic.Interaction.InputBox("Name of the variable", "Web Essentials");

            if (string.IsNullOrEmpty(name))
            {
                return(false);
            }

            using (WebEssentialsPackage.UndoContext(("Extract to variable")))
            {
                buffer.Insert(rule.Start, "@" + name + ": " + text + ";" + Environment.NewLine + Environment.NewLine);

                Span span = TextView.Selection.SelectedSpans[0].Span;
                TextView.TextBuffer.Replace(span, "@" + name);
            }

            return(true);
        }
        protected override bool Execute(uint commandId, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            ITextBuffer        buffer     = TextView.TextBuffer;
            CssEditorDocument  doc        = new CssEditorDocument(buffer);
            ICssSchemaInstance rootSchema = CssSchemaManager.SchemaManager.GetSchemaRoot(null);

            StringBuilder sb = new StringBuilder(buffer.CurrentSnapshot.Length);

            sb.Append(buffer.CurrentSnapshot.GetText());

            EditorExtensionsPackage.DTE.UndoContext.Open("Add Missing Standard Property");

            string result = AddMissingStandardDeclaration(sb, doc, rootSchema);
            Span   span   = new Span(0, buffer.CurrentSnapshot.Length);

            buffer.Replace(span, result);

            var selection = EditorExtensionsPackage.DTE.ActiveDocument.Selection as TextSelection;

            selection.GotoLine(1);

            EditorExtensionsPackage.DTE.ExecuteCommand("Edit.FormatDocument");
            EditorExtensionsPackage.DTE.UndoContext.Close();

            return(true);
        }
        protected override bool Execute(CssCommandId commandId, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            var point = TextView.GetSelection("css");

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

            ITextBuffer        buffer     = point.Value.Snapshot.TextBuffer;
            CssEditorDocument  doc        = CssEditorDocument.FromTextBuffer(buffer);
            ICssSchemaInstance rootSchema = CssSchemaManager.SchemaManager.GetSchemaRoot(null);

            StringBuilder sb             = new StringBuilder(buffer.CurrentSnapshot.GetText());
            int           scrollPosition = TextView.TextViewLines.FirstVisibleLine.Extent.Start.Position;

            using (EditorExtensionsPackage.UndoContext("Add Missing Standard Property"))
            {
                int    count;
                string result = AddMissingStandardDeclaration(sb, doc, rootSchema, out count);
                Span   span   = new Span(0, buffer.CurrentSnapshot.Length);
                buffer.Replace(span, result);

                var selection = EditorExtensionsPackage.DTE.ActiveDocument.Selection as TextSelection;
                selection.GotoLine(1);

                EditorExtensionsPackage.ExecuteCommand("Edit.FormatDocument");
                TextView.ViewScroller.ScrollViewportVerticallyByLines(ScrollDirection.Down, TextView.TextSnapshot.GetLineNumberFromPosition(scrollPosition));
                EditorExtensionsPackage.DTE.StatusBar.Text = count + " missing standard properties added";
            }

            return(true);
        }
        protected override bool Execute(uint commandId, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            if (TextView == null)
            {
                return(false);
            }

            CssEditorDocument document = CssEditorDocument.FromTextBuffer(TextView.TextBuffer);

            int       position = TextView.Caret.Position.BufferPosition.Position;
            ParseItem item     = document.Tree.StyleSheet.ItemBeforePosition(position);

            ParseItem rule = FindParent(item);
            string    text = item.Text;
            string    name = Microsoft.VisualBasic.Interaction.InputBox("Name of the variable", "Web Essentials");

            if (!string.IsNullOrEmpty(name))
            {
                EditorExtensionsPackage.DTE.UndoContext.Open("Extract to variable");

                Span span = TextView.Selection.SelectedSpans[0].Span;
                TextView.TextBuffer.Replace(span, "@" + name);
                TextView.TextBuffer.Insert(rule.Start, "@" + name + ": " + text + ";" + Environment.NewLine + Environment.NewLine);

                EditorExtensionsPackage.DTE.UndoContext.Close();

                return(true);
            }

            return(false);
        }
Esempio n. 7
0
        private static bool RemoveDuplicateProperties(StringBuilder sb, CssEditorDocument doc, out int count)
        {
            bool hasChanged = false;
            var  visitor    = new CssItemCollector <RuleBlock>(true);

            doc.Tree.StyleSheet.Accept(visitor);
            count = 0;

            foreach (RuleBlock rule in visitor.Items.Reverse())
            {
                HashSet <string> list = new HashSet <string>();

                foreach (Declaration dec in rule.Declarations.Reverse())
                {
                    if (!list.Add(dec.Text))
                    {
                        sb.Remove(dec.Start, dec.Length);
                        count++;

                        hasChanged = true;
                    }
                }
            }

            return(hasChanged);
        }
Esempio n. 8
0
        public IEnumerable <ITagSpan <ColorTag> > GetTags(NormalizedSnapshotSpanCollection spans)
        {
            if (WebEditor.Host == null || spans.Count == 0 || spans[0].Length == 0 || spans[0].Length >= _buffer.CurrentSnapshot.Length)
            {
                yield break;
            }

            var tree = CssEditorDocument.FromTextBuffer(_buffer).Tree;
            IEnumerable <ParseItem> items = GetColors(tree, spans[0]);

            foreach (var item in items.Where(i => (i.Start + i.Length) <= _buffer.CurrentSnapshot.Length))
            {
                SnapshotSpan span       = new SnapshotSpan(_buffer.CurrentSnapshot, item.Start, item.Length);
                ColorModel   colorModel = ColorParser.TryParseColor(item, ColorParser.Options.AllowAlpha | ColorParser.Options.AllowNames);
                // Fix up for rebeccapurple adornment as it isn't parsed by ColorParser currently
                if (colorModel == null && item.Text == "rebeccapurple")
                {
                    // as per http://lists.w3.org/Archives/Public/www-style/2014Jun/0312.html
                    colorModel = ColorParser.TryParseColor("#663399", ColorParser.Options.AllowAlpha | ColorParser.Options.AllowNames);
                }
                if (colorModel != null)
                {
                    yield return(new TagSpan <ColorTag>(span, new ColorTag(colorModel.Color)));
                }
            }
        }
        protected override bool Execute(uint commandId, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            ITextBuffer       buffer = ProjectHelpers.GetCurentTextBuffer();
            CssEditorDocument doc    = new CssEditorDocument(buffer);

            StringBuilder sb = new StringBuilder(buffer.CurrentSnapshot.Length);

            sb.Append(buffer.CurrentSnapshot.GetText());

            EditorExtensionsPackage.DTE.UndoContext.Open("Remove Duplicate Properties");

            string result = RemoveDuplicateProperties(sb, doc);
            Span   span   = new Span(0, buffer.CurrentSnapshot.Length);

            buffer.Replace(span, result);

            var selection = EditorExtensionsPackage.DTE.ActiveDocument.Selection as TextSelection;

            selection.GotoLine(1);

            EditorExtensionsPackage.DTE.ExecuteCommand("Edit.FormatDocument");
            EditorExtensionsPackage.DTE.UndoContext.Close();

            return(true);
        }
Esempio n. 10
0
        protected override bool Execute(CssCommandId commandId, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            var point = TextView.GetSelection("CSS");

            if (point == null)
            {
                return(false);
            }
            ITextSnapshot snapshot = point.Value.Snapshot;
            var           doc      = CssEditorDocument.FromTextBuffer(snapshot.TextBuffer);

            StringBuilder sb             = new StringBuilder(snapshot.GetText());
            int           scrollPosition = TextView.TextViewLines.FirstVisibleLine.Extent.Start.Position;

            using (EditorExtensionsPackage.UndoContext("Remove Duplicate Properties"))
            {
                int    count;
                string result = RemoveDuplicateProperties(sb, doc, out count);
                Span   span   = new Span(0, snapshot.Length);
                snapshot.TextBuffer.Replace(span, result);

                var selection = EditorExtensionsPackage.DTE.ActiveDocument.Selection as TextSelection;
                selection.GotoLine(1);

                EditorExtensionsPackage.ExecuteCommand("Edit.FormatDocument");
                TextView.ViewScroller.ScrollViewportVerticallyByLines(ScrollDirection.Down, TextView.TextSnapshot.GetLineNumberFromPosition(scrollPosition));
                EditorExtensionsPackage.DTE.StatusBar.Text = count + " duplicate properties removed";
            }

            return(true);
        }
Esempio n. 11
0
        private static bool AddMissingVendorDeclarations(StringBuilder sb, CssEditorDocument doc, ICssSchemaInstance rootSchema, out int count)
        {
            bool hasChanged = false;
            var  visitor    = new CssItemCollector <Declaration>(true);

            doc.Tree.StyleSheet.Accept(visitor);
            count = 0;

            var items = visitor.Items.Where(d => d.IsValid && !d.IsVendorSpecific() && d.PropertyName.Text != "filter");

            foreach (Declaration dec in items.Reverse())
            {
                ICssSchemaInstance schema = CssSchemaManager.SchemaManager.GetSchemaForItem(rootSchema, dec);
                var missingEntries        = dec.GetMissingVendorSpecifics(schema);

                if (missingEntries.Any())
                {
                    var    missingPrefixes = missingEntries.Select(e => e.Substring(0, e.IndexOf('-', 1) + 1));
                    string vendors         = GetVendorDeclarations(missingPrefixes, dec);

                    sb.Insert(dec.Start, vendors);
                    count++;

                    hasChanged = true;
                }
            }

            return(hasChanged);
        }
        public void AugmentSignatureHelpSession(ISignatureHelpSession session, IList <ISignature> signatures)
        {
            SnapshotPoint?point = session.GetTriggerPoint(_buffer.CurrentSnapshot);

            if (!point.HasValue)
            {
                return;
            }

            CssEditorDocument document = CssEditorDocument.FromTextBuffer(_buffer);
            ParseItem         item     = document.StyleSheet.ItemBeforePosition(point.Value.Position);

            if (item == null)
            {
                return;
            }

            Declaration dec = item.FindType <Declaration>();

            if (dec == null || dec.PropertyName == null || dec.Colon == null)
            {
                return;
            }

            foreach (ISignature signature in signatures)
            {
                if (signature is ValueOrderSignature)
                {
                    signatures.RemoveAt(signatures.Count - 1);
                    break;
                }
            }
        }
Esempio n. 13
0
        private static bool AddMissingStandardDeclaration(StringBuilder sb, CssEditorDocument doc, ICssSchemaInstance rootSchema, out int count)
        {
            bool hasChanged = false;
            var  visitor    = new CssItemCollector <RuleBlock>(true);

            doc.Tree.StyleSheet.Accept(visitor);
            count = 0;

            //var items = visitor.Items.Where(d => d.IsValid && d.IsVendorSpecific());
            foreach (RuleBlock rule in visitor.Items.Reverse())
            {
                HashSet <string> list = new HashSet <string>();
                foreach (Declaration dec in rule.Declarations.Where(d => d.IsValid && d.IsVendorSpecific()).Reverse())
                {
                    ICssSchemaInstance      schema = CssSchemaManager.SchemaManager.GetSchemaForItem(rootSchema, dec);
                    ICssCompletionListEntry entry  = VendorHelpers.GetMatchingStandardEntry(dec, schema);

                    if (entry != null && !list.Contains(entry.DisplayText) && !rule.Declarations.Any(d => d.PropertyName != null && d.PropertyName.Text == entry.DisplayText))
                    {
                        int    index    = dec.Text.IndexOf(":", StringComparison.Ordinal);
                        string standard = entry.DisplayText + dec.Text.Substring(index);

                        sb.Insert(dec.AfterEnd, standard);
                        list.Add(entry.DisplayText);
                        count++;

                        hasChanged = true;
                    }
                }
            }

            return(hasChanged);
        }
Esempio n. 14
0
 public void SubjectBuffersDisconnected(IWpfTextView textView, ConnectionReason reason, Collection <ITextBuffer> subjectBuffers)
 {
     foreach (ITextBuffer buffer in subjectBuffers)
     {
         CssEditorDocument doc = CssEditorDocument.FromTextBuffer(buffer);
         doc.Tree.TreeUpdated -= Tree_TreeUpdated;
     }
 }
        private async void GoToDefinitionCommandHandler()
        {
            var buffer         = PreviewTextHost.TextView.TextBuffer;
            var position       = PreviewTextHost.TextView.Selection.Start.Position;
            var containingLine = position.GetContainingLine();
            int line           = containingLine.LineNumber;
            var tree           = CssEditorDocument.FromTextBuffer(buffer);
            var item           = tree.StyleSheet.ItemBeforePosition(position);

            if (item == null)
            {
                return;
            }

            Selector selector = item.FindType <Selector>();

            if (selector == null)
            {
                return;
            }

            int column = Math.Max(0, selector.SimpleSelectors.Last().Start - containingLine.Start - 1);

            var sourceInfoCollection = (await _compilerResult.SourceMap).MapNodes.Where(s => s.GeneratedLine == line && s.GeneratedColumn == column);

            if (!sourceInfoCollection.Any())
            {
                if (selector.SimpleSelectors.Last().PreviousSibling == null)
                {
                    return;
                }

                // In case previous selector had > or + sign at the end,
                // LESS compiler does count it as well.
                var point = selector.SimpleSelectors.Last().PreviousSibling.AfterEnd - 1;

                column = Math.Max(0, point - containingLine.Start - 1);
                sourceInfoCollection = (await _compilerResult.SourceMap).MapNodes.Where(s => s.GeneratedLine == line && s.GeneratedColumn == column);

                if (!sourceInfoCollection.Any())
                {
                    return;
                }
            }

            var sourceInfo = sourceInfoCollection.First();

            if (sourceInfo.SourceFilePath != Document.FilePath)
            {
                FileHelpers.OpenFileInPreviewTab(sourceInfo.SourceFilePath);
            }

            string content = await FileHelpers.ReadAllTextRetry(sourceInfo.SourceFilePath);

            var finalPositionInSource = content.NthIndexOfCharInString('\n', (int)sourceInfo.OriginalLine) + sourceInfo.OriginalColumn;

            Dispatch(sourceInfo.SourceFilePath, finalPositionInSource);
        }
Esempio n. 16
0
        private void Doc_Closing(object sender, EventArgs e)
        {
            CssEditorDocument doc = sender as CssEditorDocument;

            if (doc != null)
            {
                doc.Tree.TreeUpdated -= Tree_TreeUpdated;
            }
        }
Esempio n. 17
0
 public void SubjectBuffersConnected(IWpfTextView textView, ConnectionReason reason, Collection <ITextBuffer> subjectBuffers)
 {
     foreach (ITextBuffer buffer in subjectBuffers)
     {
         CssEditorDocument doc = CssEditorDocument.FromTextBuffer(buffer);
         doc.Tree.ItemsChanged += (sender, e) => { ItemsChanged(buffer, e); };
         doc.Tree.TreeUpdated  += Tree_TreeUpdated;
         InitializeCache(doc.Tree.StyleSheet);
     }
 }
Esempio n. 18
0
        public void AugmentQuickInfoSession(IQuickInfoSession session, IList <object> qiContent, out ITrackingSpan applicableToSpan)
        {
            applicableToSpan = null;

            if (session == null || qiContent == null)
            {
                return;
            }

            // Map the trigger point down to our buffer.
            SnapshotPoint?point = session.GetTriggerPoint(_buffer.CurrentSnapshot);

            if (!point.HasValue)
            {
                return;
            }

            var       tree = CssEditorDocument.FromTextBuffer(_buffer);
            ParseItem item = tree.StyleSheet.ItemBeforePosition(point.Value.Position);

            if (item == null || !item.IsValid)
            {
                return;
            }

            Selector sel = item.FindType <Selector>();

            if (sel == null)
            {
                return;
            }

            // Mixins don't have specificity
            if (sel.SimpleSelectors.Count == 1)
            {
                var subSelectors = sel.SimpleSelectors[0].SubSelectors;

                if (subSelectors.Count == 1 &&
                    subSelectors[0] is LessMixinDeclaration &&
                    subSelectors[0] is ScssMixinDeclaration)
                {
                    return;
                }
            }

            applicableToSpan = _buffer.CurrentSnapshot.CreateTrackingSpan(item.Start, item.Length, SpanTrackingMode.EdgeNegative);

            if (_buffer.ContentType.DisplayName.Equals("css", StringComparison.OrdinalIgnoreCase))
            {
                qiContent.Add(GenerateContent(sel));
                return;
            }

            HandlePreprocessor(session, point.Value, item.FindType <Selector>(), qiContent);
        }
Esempio n. 19
0
 public void SubjectBuffersConnected(IWpfTextView textView, ConnectionReason reason, Collection <ITextBuffer> subjectBuffers)
 {
     foreach (var buffer in subjectBuffers.Where(b => b.ContentType.IsOfType("css")))
     {
         CssTreeWatcher watcher;
         if (buffer.Properties.TryGetProperty(typeof(CssTreeWatcher), out watcher))
         {
             watcher.Tree = CssEditorDocument.FromTextBuffer(buffer).Tree;
         }
     }
 }
Esempio n. 20
0
        public bool EnsureInitialized()
        {
            if (_tree == null)
            {
                try
                {
                    CssEditorDocument document = CssEditorDocument.FromTextBuffer(TextView.TextBuffer);
                    _tree = document.Tree;
                }
                catch (ArgumentNullException)
                { }
            }

            return(_tree != null);
        }
Esempio n. 21
0
        /// <summary>
        /// This must be delayed so that the TextViewConnectionListener
        /// has a chance to initialize the WebEditor host.
        /// </summary>
        public bool EnsureTreeInitialized()
        {
            if (_tree == null)
            {
                try
                {
                    CssEditorDocument document = CssEditorDocument.FromTextBuffer(_buffer);
                    _tree = document.Tree;
                }
                catch
                { }
            }

            return(_tree != null);
        }
Esempio n. 22
0
        private void UpdateAtCaretPosition(CaretPosition caretPosition)
        {
            SnapshotPoint?point = caretPosition.Point.GetPoint(_buffer, caretPosition.Affinity);

            if (!point.HasValue)
            {
                return;
            }

            var       doc  = CssEditorDocument.FromTextBuffer(_buffer);
            ParseItem item = doc.StyleSheet.ItemBeforePosition(point.Value.Position);

            if (item == null)
            {
                return;
            }

            ParseItem validItem;

            validItem = item.FindType <ItemName>()
                        ?? item.FindType <ClassSelector>()
                        ?? item.FindType <IdSelector>()
                        ?? item.FindType <LessVariableName>()
                        ?? (ParseItem)item.FindType <LessMixinName>();

            if (validItem == null)
            {
                return;
                // There is no separate token type for a property name,
                // so I need to ensure that we are in the name portion.
                //var decl = item.FindType<Declaration>();
                //if (decl != null && item.Parent != decl.PropertyName)
                //    validItem = decl.PropertyName;
                //TODO: What was this for?
            }

            // If the new caret position is still within the current word (and on the same snapshot), we don't need to check it
            if (_currentWord.HasValue &&
                _currentWord.Value.Snapshot == _view.TextSnapshot &&
                point.Value >= _currentWord.Value.Start &&
                point.Value <= _currentWord.Value.End)
            {
                return;
            }

            _requestedPoint = point.Value;
            Task.Run(new Action(() => UpdateWordAdornments(validItem)));
        }
Esempio n. 23
0
        public void AugmentSignatureHelpSession(ISignatureHelpSession session, IList <ISignature> signatures)
        {
            SnapshotPoint?point = session.GetTriggerPoint(_buffer.CurrentSnapshot);

            if (!point.HasValue)
            {
                return;
            }

            CssEditorDocument document = CssEditorDocument.FromTextBuffer(_buffer);
            ParseItem         item     = document.StyleSheet.ItemBeforePosition(point.Value.Position);

            if (item == null)
            {
                return;
            }

            Declaration dec = item.FindType <Declaration>();

            if (dec == null || dec.PropertyName == null || dec.Colon == null)
            {
                return;
            }

            int length = dec.Length - (dec.Colon.Start - dec.Start);
            var span   = _buffer.CurrentSnapshot.CreateTrackingSpan(dec.Colon.Start, length, SpanTrackingMode.EdgeNegative);

            ValueOrderFactory.AddSignatures method = ValueOrderFactory.GetMethod(dec);

            if (method != null)
            {
                signatures.Clear();
                method(session, signatures, dec, span);

                Dispatcher.CurrentDispatcher.BeginInvoke(
                    new Action(() =>
                {
                    if (session == null || session.Properties == null)
                    {
                        return;
                    }

                    session.Properties.AddProperty("dec", dec);
                    session.Match();
                }),
                    DispatcherPriority.Normal, null);
            }
        }
Esempio n. 24
0
        /// <summary>
        /// This must be delayed so that the TextViewConnectionListener
        /// has a chance to initialize the WebEditor host.
        /// </summary>
        public bool EnsureTreeInitialized()
        {
            if (_tree == null)// && WebEditor.GetHost(CssContentTypeDefinition.CssContentType) != null)
            {
                try
                {
                    CssEditorDocument document = CssEditorDocument.FromTextBuffer(_buffer);
                    _tree = document.Tree;
                }
                catch (Exception)
                {
                }
            }

            return(_tree != null);
        }
Esempio n. 25
0
        public void AugmentQuickInfoSession(IQuickInfoSession session, IList <object> qiContent, out ITrackingSpan applicableToSpan)
        {
            applicableToSpan = null;

            if (session == null || qiContent == null)
            {
                return;
            }

            // Map the trigger point down to our buffer.
            SnapshotPoint?point = session.GetTriggerPoint(_buffer.CurrentSnapshot);

            if (!point.HasValue)
            {
                return;
            }

            var       tree = CssEditorDocument.FromTextBuffer(_buffer);
            ParseItem item = tree.StyleSheet.ItemBeforePosition(point.Value.Position);

            if (item == null || !item.IsValid)
            {
                return;
            }

            Declaration dec = item.FindType <Declaration>();

            if (dec == null || !dec.IsValid || !_allowed.Contains(dec.PropertyName.Text.ToUpperInvariant()))
            {
                return;
            }

            string fontName = item.Text.Trim('\'', '"');

            if (fonts.Families.SingleOrDefault(f => f.Name.Equals(fontName, StringComparison.OrdinalIgnoreCase)) != null)
            {
                FontFamily font = new FontFamily(fontName);

                applicableToSpan = _buffer.CurrentSnapshot.CreateTrackingSpan(item.Start, item.Length, SpanTrackingMode.EdgeNegative);
                qiContent.Add(CreateFontPreview(font, 10));
                qiContent.Add(CreateFontPreview(font, 11));
                qiContent.Add(CreateFontPreview(font, 12));
                qiContent.Add(CreateFontPreview(font, 14));
                qiContent.Add(CreateFontPreview(font, 25));
                qiContent.Add(CreateFontPreview(font, 40));
            }
        }
Esempio n. 26
0
        public IEnumerable<ITagSpan<ColorTag>> GetTags(NormalizedSnapshotSpanCollection spans)
        {
            if (WebEditor.Host == null || spans.Count == 0 || spans[0].Length == 0 || spans[0].Length >= _buffer.CurrentSnapshot.Length)
                yield break;

            var tree = CssEditorDocument.FromTextBuffer(_buffer).Tree;
            IEnumerable<ParseItem> items = GetColors(tree, spans[0]);

            foreach (var item in items.Where(i => (i.Start + i.Length) <= _buffer.CurrentSnapshot.Length))
            {
                SnapshotSpan span = new SnapshotSpan(_buffer.CurrentSnapshot, item.Start, item.Length);
                ColorModel colorModel = ColorParser.TryParseColor(item, ColorParser.Options.AllowAlpha | ColorParser.Options.AllowNames);
                if (colorModel != null)
                {
                    yield return new TagSpan<ColorTag>(span, new ColorTag(colorModel.Color));
                }
            }
        }
        private static string RemoveDuplicateProperties(StringBuilder sb, CssEditorDocument doc)
        {
            var visitor = new CssItemCollector<RuleBlock>(true);
            doc.Tree.StyleSheet.Accept(visitor);

            foreach (RuleBlock rule in visitor.Items.Reverse())
            {
                HashSet<string> list = new HashSet<string>();

                foreach (Declaration dec in rule.Declarations.Reverse())
                {
                    if (!list.Add(dec.Text))
                        sb.Remove(dec.Start, dec.Length);
                }
            }

            return sb.ToString();
        }
Esempio n. 28
0
        protected override bool Execute(VSConstants.VSStd97CmdID commandId, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            var selection = TextView.GetSelection("css");

            if (selection == null)
            {
                return(false);
            }
            var       doc  = CssEditorDocument.FromTextBuffer(selection.Value.Snapshot.TextBuffer);
            ParseItem item = doc.StyleSheet.ItemBeforePosition(selection.Value);

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

            return(SchemaLookup(item, selection.Value.Snapshot.TextBuffer));
        }
Esempio n. 29
0
        public bool EnsureInitialized()
        {
            if (_tree == null && WebEditor.Host != null)
            {
                try
                {
                    CssEditorDocument document = CssEditorDocument.FromTextBuffer(_buffer);
                    _tree               = document.Tree;
                    _tree.TreeUpdated  += TreeUpdated;
                    _tree.ItemsChanged += TreeItemsChanged;
                    UpdateDeclarationCache(_tree.StyleSheet);
                }
                catch (ArgumentNullException)
                {
                }
            }

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

            if (session == null || qiContent == null)
            {
                return;
            }

            // Map the trigger point down to our buffer.
            SnapshotPoint?point = session.GetTriggerPoint(_buffer.CurrentSnapshot);

            if (!point.HasValue)
            {
                return;
            }

            var       tree = CssEditorDocument.FromTextBuffer(_buffer);
            ParseItem item = tree.StyleSheet.ItemBeforePosition(point.Value.Position);

            if (item == null || !item.IsValid)
            {
                return;
            }

            Selector sel = item.FindType <Selector>();

            if (sel == null)
            {
                return;
            }
            // Mixins don't have specificity
            if (sel.SimpleSelectors.Count == 1 && sel.SimpleSelectors[0].SubSelectors.Count == 1 && sel.SimpleSelectors[0].SubSelectors[0] is LessMixinDeclaration)
            {
                return;
            }

            applicableToSpan = _buffer.CurrentSnapshot.CreateTrackingSpan(item.Start, item.Length, SpanTrackingMode.EdgeNegative);

            string content = GenerateContent(sel);

            qiContent.Add(content);
        }
Esempio n. 31
0
        /// <summary>
        /// This must be delayed so that the TextViewConnectionListener
        /// has a chance to initialize the WebEditor host.
        /// </summary>
        public bool EnsureInitialized()
        {
            if (_tree == null && WebEditor.Host != null)
            {
                try
                {
                    CssEditorDocument document = CssEditorDocument.FromTextBuffer(_textBuffer);
                    _tree = document.Tree;

                    RegisterSmartTagProviders();

                    WebEditor.OnIdle += OnIdle;
                }
                catch (Exception)
                {
                }
            }

            return(_tree != null);
        }
Esempio n. 32
0
        public IEnumerable <ColorModel> GetColors(ITextView textView, SnapshotSpan contextSpan)
        {
            if (_directives == null && _hasFile)
            {
                ParseDocument();
            }

            if (_directives != null && textView != null)
            {
                CssEditorDocument document = CssEditorDocument.FromTextBuffer(textView.TextBuffer);
                ParseItem         item     = document.Tree.StyleSheet.ItemAfterPosition(contextSpan.Start);
                Declaration       dec      = item.FindType <Declaration>();

                if (dec != null)
                {
                    return(GetApplicableColors(dec.PropertyName.Text));
                }
            }

            return(new List <ColorModel>());
        }
Esempio n. 33
0
        protected override bool Execute(VSConstants.VSStd97CmdID commandId, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            var point = TextView.GetSelection("css");

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

            CssEditorDocument doc = CssEditorDocument.FromTextBuffer(point.Value.Snapshot.TextBuffer);

            int       position = TextView.Caret.Position.BufferPosition.Position;
            ParseItem item     = doc.Tree.StyleSheet.ItemBeforePosition(position);

            if (item != null && item.Parent != null)
            {
                string term = SearchText(item);
                FileHelpers.SearchFiles(term, "*.css;*.less;*.scss;*.sass");
            }

            return(true);
        }
        protected override bool Execute(uint commandId, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            ITextBuffer buffer = ProjectHelpers.GetCurentTextBuffer();
            CssEditorDocument doc = new CssEditorDocument(buffer);

            StringBuilder sb = new StringBuilder(buffer.CurrentSnapshot.Length);
            sb.Append(buffer.CurrentSnapshot.GetText());

            EditorExtensionsPackage.DTE.UndoContext.Open("Remove Duplicate Properties");

            string result = RemoveDuplicateProperties(sb, doc);
            Span span = new Span(0, buffer.CurrentSnapshot.Length);
            buffer.Replace(span, result);

            var selection = EditorExtensionsPackage.DTE.ActiveDocument.Selection as TextSelection;
            selection.GotoLine(1);

            EditorExtensionsPackage.DTE.ExecuteCommand("Edit.FormatDocument");
            EditorExtensionsPackage.DTE.UndoContext.Close();

            return true;
        }
        protected override bool Execute(uint commandId, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            ITextBuffer buffer = ProjectHelpers.GetCurentTextBuffer();
            CssEditorDocument doc = new CssEditorDocument(buffer);
            ICssSchemaInstance rootSchema = CssSchemaManager.SchemaManager.GetSchemaRoot(null);

            StringBuilder sb = new StringBuilder(buffer.CurrentSnapshot.Length);
            sb.Append(buffer.CurrentSnapshot.GetText());

            EditorExtensionsPackage.DTE.UndoContext.Open("Add Missing Vendor Specifics");

            string result = AddMissingVendorDeclarations(sb, doc, rootSchema);
            Span span = new Span(0, buffer.CurrentSnapshot.Length);
            buffer.Replace(span, result);

            var selection = EditorExtensionsPackage.DTE.ActiveDocument.Selection as TextSelection;
            selection.GotoLine(1);

            EditorExtensionsPackage.DTE.ExecuteCommand("Edit.FormatDocument");
            EditorExtensionsPackage.DTE.UndoContext.Close();

            return true;
        }
        public bool EnsureInitialized()
        {
            if (_tree == null && WebEditor.Host != null)
            {
                try
                {
                    _document = CssEditorDocument.FromTextBuffer(_buffer);
                    _tree = _document.Tree;
                    _buffer.PostChanged += _buffer_PostChanged;
                }
                catch (ArgumentNullException)
                {
                }
            }

            return _tree != null;
        }