private void InsertEmbedString(ITextSnapshot snapshot, string dataUri) { using (EditorExtensionsPackage.UndoContext((DisplayText))) { _span.TextBuffer.Replace(_span.GetSpan(snapshot), dataUri); } }
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; EditorExtensionsPackage.DTE.UndoContext.Open(this.DisplayText); using (var edit = textBuffer.CreateEdit()) { edit.Replace(element.Start, element.OuterRange.Length, content); edit.Apply(); } SnapshotSpan span = new SnapshotSpan(view.TextBuffer.CurrentSnapshot, start, length); view.Selection.Select(span, false); EditorExtensionsPackage.ExecuteCommand("Edit.FormatSelection"); view.Caret.MoveTo(new SnapshotPoint(view.TextBuffer.CurrentSnapshot, start)); view.Selection.Clear(); EditorExtensionsPackage.DTE.UndoContext.Close(); }
public override void Invoke() { var element = this.HtmlSmartTag.Element; var textBuffer = this.HtmlSmartTag.TextBuffer; int start = this.HtmlSmartTag.Element.Start; int length = this.HtmlSmartTag.Element.Length; string img = textBuffer.CurrentSnapshot.GetText(start, length); string figure = string.Format(_figureHtml, img); EditorExtensionsPackage.DTE.UndoContext.Open(this.DisplayText); using (var edit = textBuffer.CreateEdit()) { edit.Replace(start, length, figure); edit.Apply(); } this.HtmlSmartTag.TextView.Caret.MoveToPreviousCaretPosition(); EditorExtensionsPackage.ExecuteCommand("Edit.FormatSelection"); this.HtmlSmartTag.TextView.Caret.MoveToNextCaretPosition(); EditorExtensionsPackage.DTE.UndoContext.Close(); }
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 (EditorExtensionsPackage.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); }
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); }
protected override bool Execute(ExtractCommandId commandId, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { var point = TextView.GetSelection("SCSS"); 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 (EditorExtensionsPackage.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); }
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 (EditorExtensionsPackage.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); } }
private void InsertEmbedString(ITextSnapshot snapshot, string dataUri) { using (EditorExtensionsPackage.UndoContext((DisplayText))) { Declaration dec = _url.FindType <Declaration>(); if (dec != null && dec.Parent != null && !(dec.Parent.Parent is FontFaceDirective)) // No declaration in LESS variable definitions { RuleBlock rule = _url.FindType <RuleBlock>(); string text = dec.Text; if (dec != null && rule != null) { Declaration match = rule.Declarations.FirstOrDefault(d => d.PropertyName != null && d.PropertyName.Text == "*" + dec.PropertyName.Text); if (!text.StartsWith("*", StringComparison.Ordinal) && match == null) { _span.TextBuffer.Insert(dec.AfterEnd, "*" + text + "/* For IE 6 and 7 */"); } } } _span.TextBuffer.Replace(_span.GetSpan(snapshot), dataUri); EditorExtensionsPackage.ExecuteCommand("Edit.FormatSelection"); EditorExtensionsPackage.ExecuteCommand("Edit.CollapsetoDefinitions"); } }
public override void Invoke() { Span ruleSpan = new Span(_selector.Start, _index); using (EditorExtensionsPackage.UndoContext((DisplayText))) _span.TextBuffer.Delete(ruleSpan); }
protected override bool Execute(CssCommandId commandId, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { var point = TextView.GetSelection("css"); if (point == null) { return(false); } var buffer = point.Value.Snapshot.TextBuffer; int scrollPosition = TextView.TextViewLines.FirstVisibleLine.Extent.Start.Position; using (EditorExtensionsPackage.UndoContext("Sort All Properties")) { string result = SortProperties(buffer.CurrentSnapshot.GetText(), buffer.ContentType); Span span = new Span(0, buffer.CurrentSnapshot.Length); buffer.Replace(span, result); EditorExtensionsPackage.ExecuteCommand("Edit.FormatDocument"); var selection = EditorExtensionsPackage.DTE.ActiveDocument.Selection as TextSelection; selection.GotoLine(1); TextView.ViewScroller.ScrollViewportVerticallyByLines(ScrollDirection.Down, TextView.TextSnapshot.GetLineNumberFromPosition(scrollPosition)); EditorExtensionsPackage.DTE.StatusBar.Text = "Properties sorted"; } 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); }
private static void Replace(ITrackingSpan contextSpan, ITextView textView, string atDirective, string fontFamily) { using (EditorExtensionsPackage.UndoContext(("Embed font"))) { textView.TextBuffer.Insert(0, atDirective + Environment.NewLine + Environment.NewLine); textView.TextBuffer.Insert(contextSpan.GetSpan(textView.TextBuffer.CurrentSnapshot).Start, fontFamily); } }
private static async Task UpdateSheetRulesAsync(string file, IEnumerable <CssSelectorChangeData> set) { ////Get off the UI thread //await Task.Factory.StartNew(() => { }); var doc = DocumentFactory.GetDocument(file, true); if (doc == null) { return; } var oldSnapshotOnChange = doc.IsProcessingUnusedCssRules; var window = EditorExtensionsPackage.DTE.ItemOperations.OpenFile(file); window.Activate(); var buffer = ProjectHelpers.GetCurentTextBuffer(); var flattenedRules = FlattenRules(doc); var allEdits = new List <CssRuleBlockSyncAction>(); doc.IsProcessingUnusedCssRules = false; doc.Reparse(buffer.CurrentSnapshot.GetText()); foreach (var item in set) { var selectorName = RuleRegistry.StandardizeSelector(item.Rule); var matchingRules = flattenedRules.Where(x => string.Equals(x.CleansedSelectorName, selectorName, StringComparison.Ordinal)).OrderBy(x => x.Offset).ToList(); var rule = matchingRules[item.RuleIndex]; var actions = await CssRuleDefinitionSync.ComputeSyncActionsAsync(rule.Source, item.NewValue, item.OldValue); allEdits.AddRange(actions); } var compositeEdit = buffer.CreateEdit(); try { foreach (var action in allEdits) { action(window, compositeEdit); } } catch { compositeEdit.Cancel(); } finally { if (!compositeEdit.Canceled) { compositeEdit.Apply(); EditorExtensionsPackage.ExecuteCommand("Edit.FormatDocument"); window.Document.Save(); } } //await Task.Delay(2000); //<-- Try to wait for the files to actually save doc.IsProcessingUnusedCssRules = oldSnapshotOnChange; }
private void InsertEmbedString(ITextSnapshot snapshot, string dataUri) { using (EditorExtensionsPackage.UndoContext((DisplayText))) { _span.TextBuffer.Replace(_span.GetSpan(snapshot), dataUri); EditorExtensionsPackage.ExecuteCommand("Edit.FormatSelection"); EditorExtensionsPackage.ExecuteCommand("Edit.CollapsetoDefinitions"); } }
private static void UpdateSpan(SnapshotSpan span, string result, string undoTitle) { if (result.Length > 1) { result = result.TrimStart('0'); } using (EditorExtensionsPackage.UndoContext(undoTitle)) span.Snapshot.TextBuffer.Replace(span, result); }
public override void Invoke() { string separator = Microsoft.CSS.Editor.CssSettings.FormatterBlockBracePosition == BracePosition.Compact ? " " : Environment.NewLine; string insert = _lastVendor.Text + separator + _standard.Text; using (EditorExtensionsPackage.UndoContext((DisplayText))) { _span.TextBuffer.Replace(new Span(_lastVendor.Start, _lastVendor.Length), insert); _span.TextBuffer.Delete(new Span(_standard.Start, _standard.Length)); EditorExtensionsPackage.ExecuteCommand("Edit.FormatSelection"); } }
private static IVsHierarchy ResolveVsHierarchyItem(string projectName) { IVsHierarchy hierarchyItem = null; var solution = EditorExtensionsPackage.GetGlobalService <IVsSolution>(typeof(SVsSolution)); if (solution != null) { ErrorHandler.ThrowOnFailure(solution.GetProjectOfUniqueName(projectName, out hierarchyItem)); } return(hierarchyItem); }
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 (EditorExtensionsPackage.UndoContext((this.DisplayText))) textBuffer.Replace(range.ToSpan(), result); }
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 (EditorExtensionsPackage.UndoContext((DisplayText))) { SnapshotSpan span = _span.GetSpan(_span.TextBuffer.CurrentSnapshot); _span.TextBuffer.Replace(span, _declaration.Text + separator + newDec); EditorExtensionsPackage.ExecuteCommand("Edit.FormatSelection"); } }
private void Minify() { string text = _buffer.CurrentSnapshot.GetText(); text = Regex.Replace(text, @"(},|};|}\s+|\),|\);|}(?=\w)|(?=if\())", "$1" + Environment.NewLine); using (EditorExtensionsPackage.UndoContext("Un-Minify")) { Span span = new Span(0, _buffer.CurrentSnapshot.Length); _buffer.Replace(span, text); EditorExtensionsPackage.ExecuteCommand("Edit.FormatDocument"); } }
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 (EditorExtensionsPackage.UndoContext((DisplayText))) _span.TextBuffer.Replace(new Span(_directive.Start, _directive.Length), sb.ToString() + _directive.Text); }
public override void Invoke() { using (EditorExtensionsPackage.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); } }
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 (EditorExtensionsPackage.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); EditorExtensionsPackage.ExecuteCommand("Edit.FormatSelection"); } }
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 (EditorExtensionsPackage.UndoContext((DisplayText))) ReplaceUrlValue(fileName); } }
private string GetOutputFileName() { if (!string.IsNullOrEmpty(_outputFile)) { return(_outputFile); } IVsSolution solution = EditorExtensionsPackage.GetGlobalService <IVsSolution>(typeof(SVsSolution)); Project project = ProjectHelpers.GetProject(SourceFilePath); IVsHierarchy hierarchy = null; if (project != null && solution.GetProjectOfUniqueName(project.UniqueName, out hierarchy) != VSConstants.S_OK) { return(string.Empty); } IVsBuildPropertyStorage buildPropertyStorage = hierarchy as IVsBuildPropertyStorage; if (buildPropertyStorage == null) { _outputFile = Path.ChangeExtension(SourceFilePath, ".js"); } else { string outputFile, outputDir; string config = EditorExtensionsPackage.DTE.Solution.SolutionBuild.ActiveConfiguration.Name; int resultFile = buildPropertyStorage.GetPropertyValue("TypeScriptOutFile", config, (uint)_PersistStorageType.PST_PROJECT_FILE, out outputFile); int resultDir = buildPropertyStorage.GetPropertyValue("TypeScriptOutDir", config, (uint)_PersistStorageType.PST_PROJECT_FILE, out outputDir); if (!string.IsNullOrEmpty(outputFile) && resultFile == VSConstants.S_OK) { _outputFile = Path.Combine(ProjectHelpers.GetRootFolder(project), outputFile); } else if (!string.IsNullOrEmpty(outputDir) && resultDir == VSConstants.S_OK) { string dir = Path.Combine(ProjectHelpers.GetRootFolder(project), outputDir); string file = Path.ChangeExtension(Path.GetFileName(SourceFilePath), ".js"); _outputFile = Path.Combine(dir, file); } } if (string.IsNullOrEmpty(_outputFile)) { _outputFile = Path.ChangeExtension(SourceFilePath, ".js"); } return(_outputFile); }
protected override bool Execute(ExtractCommandId commandId, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { if (TextView == null) { return(false); } string content = TextView.Selection.SelectedSpans[0].GetText(); string extension = Path.GetExtension(_dte.ActiveDocument.FullName).ToLowerInvariant(); if (!_possible.Contains(extension.ToUpperInvariant())) { extension = ".css"; } string name = Interaction.InputBox("Specify the name of the file", "Web Essentials", "file1" + extension).Trim(); if (!string.IsNullOrEmpty(name)) { if (string.IsNullOrEmpty(Path.GetExtension(name))) { name = name + extension; } string fileName = Path.Combine(Path.GetDirectoryName(_dte.ActiveDocument.FullName), name); if (!File.Exists(fileName)) { using (EditorExtensionsPackage.UndoContext("Extract to file...")) { using (StreamWriter writer = new StreamWriter(fileName, false, new UTF8Encoding(true))) { writer.Write(content); } ProjectHelpers.AddFileToActiveProject(fileName); TextView.TextBuffer.Delete(TextView.Selection.SelectedSpans[0].Span); _dte.ItemOperations.OpenFile(fileName); } } else { Logger.ShowMessage("The file already exists."); } } return(true); }
private void 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 (EditorExtensionsPackage.UndoContext((this.DisplayText))) { textBuffer.Replace(new Span(element.Start, element.Length), reference); File.WriteAllText(fileName, text, Encoding.UTF8); EditorExtensionsPackage.DTE.ItemOperations.OpenFile(fileName); ProjectHelpers.AddFileToActiveProject(fileName); } }
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 (EditorExtensionsPackage.UndoContext((DisplayText))) ReplaceUrlValue(fileName, textBuffer, src); } }
public override void Invoke() { var element = this.HtmlSmartTag.Element; var textBuffer = this.HtmlSmartTag.TextBuffer; EditorExtensionsPackage.DTE.UndoContext.Open(this.DisplayText); using (var edit = textBuffer.CreateEdit()) { Unminify(element, edit); edit.Apply(); } EditorExtensionsPackage.ExecuteCommand("Edit.FormatSelection"); EditorExtensionsPackage.DTE.UndoContext.Close(); }
private void Update(int start, int end) { using (EditorExtensionsPackage.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); EditorExtensionsPackage.ExecuteCommand("Edit.FormatSelection"); } }