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); } } }
/// <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); }
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); }
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); }
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); } }
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); }
private void InsertEmbedString(ITextSnapshot snapshot, string dataUri) { using (WebEssentialsPackage.UndoContext((DisplayText))) { _span.TextBuffer.Replace(_span.GetSpan(snapshot), dataUri); } }
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); } }
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); } }
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 = WebEssentialsPackage.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(); WebEssentialsPackage.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 (WebEssentialsPackage.UndoContext((DisplayText))) { _span.TextBuffer.Replace(_span.GetSpan(snapshot), dataUri); WebEssentialsPackage.ExecuteCommand("Edit.FormatSelection"); WebEssentialsPackage.ExecuteCommand("Edit.CollapsetoDefinitions"); } }
private void Retrigger() { if (_broker.IsCompletionActive(_textView)) { return; } WebEssentialsPackage.ExecuteCommand("Edit.ListMembers"); }
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); }
private static IVsHierarchy ResolveVsHierarchyItem(string projectName) { IVsHierarchy hierarchyItem = null; var solution = WebEssentialsPackage.GetGlobalService <IVsSolution>(typeof(SVsSolution)); if (solution != null) { ErrorHandler.ThrowOnFailure(solution.GetProjectOfUniqueName(projectName, out hierarchyItem)); } return(hierarchyItem); }
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"); } }
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"); } }
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"); } }
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); } }
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); }
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); }
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"); } }
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); } }
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(); } } }
private string GetOutputFileName() { if (!string.IsNullOrEmpty(_outputFile)) { return(_outputFile); } IVsSolution solution = WebEssentialsPackage.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 = WebEssentialsPackage.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); }
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); } }
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); } }
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"); } }
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(); } } }
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(); } } }
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(); } }