コード例 #1
0
        private void UpdateTextBuffer(string fileName, string relativeTo)
        {
            int    position = TextView.Caret.Position.BufferPosition.Position;
            string relative = MakeRelative(relativeTo, fileName);
            string altText  = PrettifyAltText(fileName);
            string text     = string.Format(CultureInfo.InvariantCulture, _format, relative, altText);

            using (WebEssentialsPackage.UndoContext("Insert Image"))
            {
                try
                {
                    TextView.TextBuffer.Insert(position, text);

                    SnapshotSpan span = new SnapshotSpan(TextView.TextBuffer.CurrentSnapshot, position, _format.Length);
                    TextView.Selection.Select(span, false);

                    WebEssentialsPackage.ExecuteCommand("Edit.FormatSelection");
                    TextView.Selection.Clear();
                }
                catch (Exception ex)
                {
                    Logger.Log(ex);
                }
            }
        }
コード例 #2
0
        /// <summary>
        /// Insert a link (relative to the current document) into the text view buffer
        /// using the content type to select the right format (HTML, CSS, Markdown, etc..).
        /// </summary>
        /// <param name="textView"></param>
        /// <param name="absoluteImageFilePath"></param>
        public static bool InsertLinkToImageFile(this IWpfTextView textView, string absoluteImageFilePath)
        {
            string relative = GetRelativeEncodedUrl(absoluteImageFilePath);

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

            string format   = GetFormat(textView);
            int    position = textView.Caret.Position.BufferPosition.Position;

            string text = string.Format(CultureInfo.InvariantCulture, format, relative, Path.GetFileName(absoluteImageFilePath));

            using (WebEssentialsPackage.UndoContext("Insert Image"))
            {
                textView.TextBuffer.Insert(position, text);

                try
                {
                    SnapshotSpan span = new SnapshotSpan(textView.TextBuffer.CurrentSnapshot, position, format.Length);
                    textView.Selection.Select(span, false);

                    WebEssentialsPackage.ExecuteCommand("Edit.FormatSelection");
                    textView.Selection.Clear();
                }
                catch
                {
                    // Try to format the selection. Some editors handle this differently, so try/catch
                }
            }
            return(true);
        }
コード例 #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);
        }
コード例 #4
0
            public async override void Invoke()
            {
                ITextBuffer     textBuffer = this.HtmlSmartTag.TextBuffer;
                ElementNode     element    = this.HtmlSmartTag.Element;
                AttributeNode   src        = element.GetAttribute("src", true);
                ImageCompressor compressor = new ImageCompressor();

                bool isDataUri = src.Value.StartsWith("data:image/", StringComparison.Ordinal);

                if (isDataUri)
                {
                    string dataUri = await compressor.CompressDataUriAsync(src.Value);

                    if (dataUri.Length < src.Value.Length)
                    {
                        using (WebEssentialsPackage.UndoContext("Optimize image"))
                        {
                            Span span = Span.FromBounds(src.ValueRangeUnquoted.Start, src.ValueRangeUnquoted.End);
                            textBuffer.Replace(span, dataUri);
                        }
                    }
                }
                else
                {
                    var fileName = ImageQuickInfo.GetFullUrl(src.Value, textBuffer);

                    if (string.IsNullOrEmpty(fileName) || !ImageCompressor.IsFileSupported(fileName) || !File.Exists(fileName))
                    {
                        return;
                    }

                    await compressor.CompressFilesAsync(fileName);
                }
            }
コード例 #5
0
        public async override void Invoke(CancellationToken cancellationToken)
        {
            ImageCompressor compressor = new ImageCompressor();

            bool isDataUri = Attribute.Value.StartsWith("data:image/", StringComparison.Ordinal);

            if (isDataUri)
            {
                string dataUri = await compressor.CompressDataUriAsync(Attribute.Value);

                if (dataUri.Length < Attribute.Value.Length)
                {
                    using (WebEssentialsPackage.UndoContext(this.DisplayText))
                        using (ITextEdit edit = TextBuffer.CreateEdit())
                        {
                            Span span = Span.FromBounds(Attribute.ValueRangeUnquoted.Start, Attribute.ValueRangeUnquoted.End);
                            edit.Replace(span, dataUri);
                            edit.Apply();
                        }
                }
            }
            else
            {
                var fileName = ImageQuickInfo.GetFullUrl(Attribute.Value, TextBuffer);

                if (string.IsNullOrEmpty(fileName) || !ImageCompressor.IsFileSupported(fileName) || !File.Exists(fileName))
                {
                    return;
                }

                await compressor.CompressFilesAsync(fileName);
            }
        }
コード例 #6
0
        protected override bool Execute(VSConstants.VSStd2KCmdID commandId, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            if (_broker.IsCompletionActive(TextView))
            {
                return(false);
            }

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

            if (position == 0 || position == TextView.TextBuffer.CurrentSnapshot.Length || TextView.Selection.SelectedSpans[0].Length > 0)
            {
                return(false);
            }

            char before = TextView.TextBuffer.CurrentSnapshot.GetText(position - 1, 1)[0];
            char after  = TextView.TextBuffer.CurrentSnapshot.GetText(position, 1)[0];

            if (before == '{' && after == '}')
            {
                Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
                {
                    using (WebEssentialsPackage.UndoContext("Smart Indent"))
                    {
                        // HACK: A better way is needed.
                        // We do this to get around the native TS formatter
                        SendKeys.Send("{TAB}{ENTER}{UP}");
                    }
                }), DispatcherPriority.Normal, null);
            }

            return(false);
        }
コード例 #7
0
 private void InsertEmbedString(ITextSnapshot snapshot, string dataUri)
 {
     using (WebEssentialsPackage.UndoContext((DisplayText)))
     {
         _span.TextBuffer.Replace(_span.GetSpan(snapshot), dataUri);
     }
 }
コード例 #8
0
 private static void Replace(ITrackingSpan contextSpan, ITextView textView, string atDirective, string fontFamily)
 {
     using (WebEssentialsPackage.UndoContext(("Embed font")))
     {
         textView.TextBuffer.Insert(0, atDirective + Environment.NewLine + Environment.NewLine);
         textView.TextBuffer.Insert(contextSpan.GetSpan(textView.TextBuffer.CurrentSnapshot).Start, fontFamily);
     }
 }
コード例 #9
0
 private void InsertEmbedString(ITextSnapshot snapshot, string dataUri)
 {
     using (WebEssentialsPackage.UndoContext((DisplayText)))
     {
         _span.TextBuffer.Replace(_span.GetSpan(snapshot), dataUri);
         WebEssentialsPackage.ExecuteCommand("Edit.FormatSelection");
         WebEssentialsPackage.ExecuteCommand("Edit.CollapsetoDefinitions");
     }
 }
コード例 #10
0
        private static void UpdateSpan(SnapshotSpan span, string result, string undoTitle)
        {
            if (result.Length > 1)
            {
                result = result.TrimStart('0');
            }

            using (WebEssentialsPackage.UndoContext(undoTitle))
                span.Snapshot.TextBuffer.Replace(span, result);
        }
コード例 #11
0
 public override void Invoke()
 {
     using (WebEssentialsPackage.UndoContext((DisplayText)))
     {
         var snapshot = _span.TextBuffer.CurrentSnapshot;
         var position = _rule.Start + _rule.Length;
         var start    = CalculateDeletionStartFromStartPosition(snapshot, _rule.Start);
         var end      = CalculateDeletionEndFromRuleEndPosition(snapshot, position);
         var length   = end - start;
         var ss       = new SnapshotSpan(snapshot, start, length);
         _span.TextBuffer.Delete(ss);
     }
 }
コード例 #12
0
        public override void Invoke()
        {
            StringBuilder sb = new StringBuilder();

            foreach (var entry in _prefixes)
            {
                string text = _directive.Text.Replace("@" + _directive.Keyword.Text, entry);
                sb.Append(text + Environment.NewLine + Environment.NewLine);
            }

            using (WebEssentialsPackage.UndoContext((DisplayText)))
                _span.TextBuffer.Replace(new Span(_directive.Start, _directive.Length), sb.ToString() + _directive.Text);
        }
コード例 #13
0
        public override void Invoke()
        {
            string separator = CssSettings.Get(_span.TextBuffer).FormatterBlockBracePosition == BracePosition.Compact ? " " : Environment.NewLine;
            //string separator = CssSettings.FormatterBlockBracePosition == BracePosition.Compact ? " " : Environment.NewLine;
            string insert = _lastVendor.Text + separator + _standard.Text;

            using (WebEssentialsPackage.UndoContext((DisplayText)))
            {
                _span.TextBuffer.Replace(new Span(_lastVendor.Start, _lastVendor.Length), insert);
                _span.TextBuffer.Delete(new Span(_standard.Start, _standard.Length));
                WebEssentialsPackage.ExecuteCommand("Edit.FormatSelection");
            }
        }
コード例 #14
0
        public override void Invoke()
        {
            string separator = _declaration.Parent.Text.Contains("\r") || _declaration.Parent.Text.Contains("\n") ? Environment.NewLine : " ";
            int    index     = _declaration.Text.IndexOf(":", StringComparison.Ordinal);
            string newDec    = _standardName + _declaration.Text.Substring(index);

            using (WebEssentialsPackage.UndoContext((DisplayText)))
            {
                SnapshotSpan span = _span.GetSpan(_span.TextBuffer.CurrentSnapshot);
                _span.TextBuffer.Replace(span, _declaration.Text + separator + newDec);
                WebEssentialsPackage.ExecuteCommand("Edit.FormatSelection");
            }
        }
コード例 #15
0
            public override void Invoke()
            {
                var element    = this.HtmlSmartTag.Element;
                var textBuffer = this.HtmlSmartTag.TextBuffer;

                ITextRange    range    = element.InnerRange;
                string        text     = textBuffer.CurrentSnapshot.GetText(range.Start, range.Length);
                IFileMinifier minifier = element.IsScriptBlock() ? (IFileMinifier) new JavaScriptFileMinifier() : new CssFileMinifier();
                string        result   = minifier.MinifyString(text);

                using (WebEssentialsPackage.UndoContext((this.DisplayText)))
                    textBuffer.Replace(range.ToSpan(), result);
            }
コード例 #16
0
        private void Minify()
        {
            string text = _buffer.CurrentSnapshot.GetText();

            text = Regex.Replace(text, @"(},|};|}\s+|\),|\);|}(?=\w)|(?=if\())", "$1" + Environment.NewLine);

            using (WebEssentialsPackage.UndoContext("Un-Minify"))
            {
                Span span = new Span(0, _buffer.CurrentSnapshot.Length);
                _buffer.Replace(span, text);
                WebEssentialsPackage.ExecuteCommand("Edit.FormatDocument");
            }
        }
コード例 #17
0
        public override void Invoke()
        {
            //string separator = _directive.Parent.Text.Contains("\r") || _directive.Parent.Text.Contains("\n") ? Environment.NewLine : " ";
            //int index = _directive.Text.IndexOf(":", StringComparison.Ordinal);
            //string newDec = _standardName + _directive.Text.Substring(index);

            using (WebEssentialsPackage.UndoContext((DisplayText)))
            {
                //SnapshotSpan span = _span.GetSpan(_span.TextBuffer.CurrentSnapshot);
                string text = _directive.Text.Replace("@" + _directive.Keyword.Text, _standardName);
                _span.TextBuffer.Insert(_directive.AfterEnd, Environment.NewLine + Environment.NewLine + text);
                WebEssentialsPackage.ExecuteCommand("Edit.FormatSelection");
            }
        }
コード例 #18
0
        public async override void Invoke()
        {
            string base64    = _url.UrlString.Text.Trim('\'', '"');
            string mimeType  = FileHelpers.GetMimeTypeFromBase64(base64);
            string extension = FileHelpers.GetExtension(mimeType) ?? "png";

            var fileName = FileHelpers.ShowDialog(extension);

            if (!string.IsNullOrEmpty(fileName) && await FileHelpers.SaveDataUriToFile(base64, fileName))
            {
                using (WebEssentialsPackage.UndoContext((DisplayText)))
                    ReplaceUrlValue(fileName);
            }
        }
コード例 #19
0
        public override void Invoke(CancellationToken cancellationToken)
        {
            string        text     = Element.GetText(Element.InnerRange);
            IFileMinifier minifier = Element.IsScriptBlock() ? (IFileMinifier) new JavaScriptFileMinifier() : new CssFileMinifier();
            string        result   = minifier.MinifyString(text);

            using (WebEssentialsPackage.UndoContext((this.DisplayText)))
            {
                using (ITextEdit edit = TextBuffer.CreateEdit())
                {
                    edit.Replace(Element.InnerRange.ToSpan(), result);
                    edit.Apply();
                }
            }
        }
コード例 #20
0
ファイル: Base64DecodeSmartTag.cs プロジェクト: waodng/VSIX
            public async override void Invoke()
            {
                ITextBuffer   textBuffer = this.HtmlSmartTag.TextBuffer;
                ElementNode   element    = this.HtmlSmartTag.Element;
                AttributeNode src        = element.GetAttribute("src", true);

                string mimeType  = FileHelpers.GetMimeTypeFromBase64(src.Value);
                string extension = FileHelpers.GetExtension(mimeType) ?? "png";

                var fileName = FileHelpers.ShowDialog(extension);

                if (!string.IsNullOrEmpty(fileName) && await FileHelpers.SaveDataUriToFile(src.Value, fileName))
                {
                    using (WebEssentialsPackage.UndoContext((DisplayText)))
                        ReplaceUrlValue(fileName, textBuffer, src);
                }
            }
コード例 #21
0
ファイル: ExtractToFileSmartTag.cs プロジェクト: waodng/VSIX
            private async Task MakeChanges(string root, string fileName)
            {
                var    element    = this.HtmlSmartTag.Element;
                var    textBuffer = this.HtmlSmartTag.TextBuffer;
                string text       = textBuffer.CurrentSnapshot.GetText(element.InnerRange.Start, element.InnerRange.Length);

                string reference = GetReference(element, fileName, root);

                using (WebEssentialsPackage.UndoContext((this.DisplayText)))
                {
                    textBuffer.Replace(new Span(element.Start, element.Length), reference);
                    await FileHelpers.WriteAllTextRetry(fileName, text);

                    WebEssentialsPackage.DTE.ItemOperations.OpenFile(fileName);
                    ProjectHelpers.AddFileToActiveProject(fileName);
                }
            }
コード例 #22
0
ファイル: SurroundWithTarget.cs プロジェクト: waodng/VSIX
        private void Update(int start, int end)
        {
            using (WebEssentialsPackage.UndoContext("Surround with..."))
            {
                using (var edit = _buffer.CreateEdit())
                {
                    edit.Insert(end, "</div>");
                    edit.Insert(start, "<div>");
                    edit.Apply();
                }

                SnapshotPoint point = new SnapshotPoint(_buffer.CurrentSnapshot, start + 1);

                _view.Caret.MoveTo(point);
                _view.Selection.Select(new SnapshotSpan(_buffer.CurrentSnapshot, point, 3), false);
                WebEssentialsPackage.ExecuteCommand("Edit.FormatSelection");
            }
        }
コード例 #23
0
        public override void Invoke(CancellationToken cancellationToken)
        {
            AttributeNode src         = Element.GetAttribute("src") ?? Element.GetAttribute("href");
            AttributeNode integrity   = Element.GetAttribute("integrity");
            AttributeNode crossorigin = Element.GetAttribute("crossorigin");

            string url = src.Value;

            if (url.StartsWith("//"))
            {
                url = "http:" + url;
            }

            string hash = CalculateHash(url);

            if (string.IsNullOrEmpty(hash))
            {
                MessageBox.Show("Could not resolve the URL to generate the hash", "Web Essentials", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            using (WebEssentialsPackage.UndoContext((DisplayText)))
            {
                using (ITextEdit edit = TextBuffer.CreateEdit())
                {
                    if (integrity != null)
                    {
                        Span span = new Span(integrity.ValueRangeUnquoted.Start, integrity.ValueRangeUnquoted.Length);
                        edit.Replace(span, hash);
                    }
                    else
                    {
                        edit.Insert(src.ValueRange.End, " integrity=\"" + hash + "\"");
                    }

                    if (crossorigin == null)
                    {
                        edit.Insert(src.ValueRange.End, " crossorigin=\"anonymous\"");
                    }

                    edit.Apply();
                }
            }
        }
コード例 #24
0
        public async override void Invoke(CancellationToken cancellationToken)
        {
            string mimeType  = FileHelpers.GetMimeTypeFromBase64(Attribute.Value);
            string extension = FileHelpers.GetExtension(mimeType) ?? "png";

            var fileName = FileHelpers.ShowDialog(extension);

            if (!string.IsNullOrEmpty(fileName) && await FileHelpers.SaveDataUriToFile(Attribute.Value, fileName))
            {
                string relative = FileHelpers.RelativePath(TextBuffer.GetFileName(), fileName);

                using (WebEssentialsPackage.UndoContext((this.DisplayText)))
                    using (ITextEdit edit = TextBuffer.CreateEdit())
                    {
                        edit.Replace(Attribute.ValueRangeUnquoted.ToSpan(), relative.ToLowerInvariant());
                        edit.Apply();
                    }
            }
        }
コード例 #25
0
        private void InsertMissingQuotes(IEnumerable <JSONMember> properties)
        {
            using (WebEssentialsPackage.UndoContext("Inserting missing quotes"))
            {
                var edit = TextView.TextBuffer.CreateEdit();

                foreach (var prop in properties)
                {
                    string text = prop.Name.Text;

                    if (!text.EndsWith("\"", StringComparison.Ordinal) && !text.StartsWith("\"", StringComparison.Ordinal))
                    {
                        edit.Replace(prop.Name.Start, prop.Name.Length, "\"" + prop.Name.Text + "\"");
                    }
                }

                edit.Apply();
            }
        }
コード例 #26
0
        public override void Invoke()
        {
            ParseItem rule = FindParent(_item);
            string    text = _item.Text;
            string    name = Microsoft.VisualBasic.Interaction.InputBox("Name of the variable", "Web Essentials");

            if (!string.IsNullOrEmpty(name))
            {
                using (WebEssentialsPackage.UndoContext((DisplayText)))
                {
                    foreach (ParseItem item in FindItems())
                    {
                        Span span = new Span(item.Start, item.Length);
                        _span.TextBuffer.Replace(span, _variableToken + name);
                    }

                    _span.TextBuffer.Insert(rule.Start, _variableToken + name + ": " + text + ";" + Environment.NewLine + Environment.NewLine);
                }
            }
        }
コード例 #27
0
        public override void Invoke()
        {
            RuleBlock     rule      = _declaration.FindType <RuleBlock>();
            StringBuilder sb        = new StringBuilder();
            string        separator = rule.Text.Contains("\r") || rule.Text.Contains("\n") ? Environment.NewLine : " ";

            foreach (var entry in _prefixes)
            {
                sb.Append(entry + _declaration.Text + separator);
            }

            using (WebEssentialsPackage.UndoContext((DisplayText)))
            {
                _span.TextBuffer.Replace(_span.GetSpan(_span.TextBuffer.CurrentSnapshot), sb.ToString() + _declaration.Text);
                if (separator == Environment.NewLine)
                {
                    WebEssentialsPackage.ExecuteCommand("Edit.FormatSelection");
                }
            }
        }
コード例 #28
0
        public override void Invoke(CancellationToken cancellationToken)
        {
            var content = Element.GetText(Element.InnerRange).Trim();
            int start   = Element.Start;
            int length  = content.Length;

            using (WebEssentialsPackage.UndoContext((this.DisplayText)))
            {
                using (ITextEdit edit = TextBuffer.CreateEdit())
                {
                    edit.Replace(Element.OuterRange.ToSpan(), content);
                    edit.Apply();
                }

                SnapshotSpan span = new SnapshotSpan(TextView.TextBuffer.CurrentSnapshot, start, length);

                TextView.Selection.Select(span, false);
                WebEssentialsPackage.ExecuteCommand("Edit.FormatSelection");
                TextView.Caret.MoveTo(new SnapshotPoint(TextView.TextBuffer.CurrentSnapshot, start));
                TextView.Selection.Clear();
            }
        }
コード例 #29
0
            public override void Invoke()
            {
                var element    = HtmlSmartTag.Element;
                var textBuffer = HtmlSmartTag.TextBuffer;
                var view       = HtmlSmartTag.TextView;

                var content = textBuffer.CurrentSnapshot.GetText(element.InnerRange.Start, element.InnerRange.Length).Trim();
                int start   = element.Start;
                int length  = content.Length;

                using (WebEssentialsPackage.UndoContext((this.DisplayText)))
                {
                    textBuffer.Replace(new Span(element.Start, element.OuterRange.Length), content);

                    SnapshotSpan span = new SnapshotSpan(view.TextBuffer.CurrentSnapshot, start, length);

                    view.Selection.Select(span, false);
                    WebEssentialsPackage.ExecuteCommand("Edit.FormatSelection");
                    view.Caret.MoveTo(new SnapshotPoint(view.TextBuffer.CurrentSnapshot, start));
                    view.Selection.Clear();
                }
            }
コード例 #30
0
        private async Task MakeChanges(string root, string fileName)
        {
            string text      = Element.GetText(Element.InnerRange).Trim();
            string reference = GetReference(Element, fileName, root);

            using (WebEssentialsPackage.UndoContext((this.DisplayText)))
            {
                using (ITextEdit edit = TextBuffer.CreateEdit())
                {
                    edit.Replace(new Span(Element.Start, Element.Length), reference);
                    edit.Apply();
                }

                await FileHelpers.WriteAllTextRetry(fileName, text);

                ProjectHelpers.AddFileToActiveProject(fileName);
                WebEssentialsPackage.DTE.ItemOperations.OpenFile(fileName);

                await Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => {
                    WebEssentialsPackage.ExecuteCommand("Edit.FormatDocument");
                }), DispatcherPriority.ApplicationIdle, null);
            }
        }