/// <include file='doc\ExpansionProvider.uex' path='docs/doc[@for="ExpansionProvider.FormatSpan"]/*' /> public virtual int FormatSpan(IVsTextLines buffer, TextSpan[] ts) { if (this.source.GetTextLines() != buffer) { throw new System.ArgumentException(SR.GetString(SR.UnknownBuffer), "buffer"); } int rc = NativeMethods.E_NOTIMPL; if (ts != null) { for (int i = 0, n = ts.Length; i < n; i++) { if (this.source.LanguageService.Preferences.EnableFormatSelection) { TextSpan span = ts[i]; // We should not merge edits in this case because it might clobber the // $varname$ spans which are markers for yellow boxes. using (EditArray edits = new EditArray(this.source, this.view, false, SR.GetString(SR.FormatSpan))) { this.source.ReformatSpan(edits, span); edits.ApplyEdits(); } rc = NativeMethods.S_OK; } } } return(rc); }
/// <summary> /// Reformat the text buffer /// </summary> private void FormatBuffer(Microsoft.VisualStudio.Package.Source src) { using (var edits = new EditArray(src, null, false, "Reformat")) { var span = src.GetDocumentSpan(); src.ReformatSpan(edits, span); } }
public override void ReformatSpan(EditArray mgr, TextSpan span) { var ca = new CompoundAction(this, "Reformat code"); using(ca) { ca.FlushEditActions(); Data.ReformatSpan(mgr, span, _parent.Package.CreateFormattingProvider()); } }
public override void ReformatSpan(EditArray mgr, TextSpan span) { string description = "Reformat code"; CompoundAction ca = new CompoundAction(this, description); using (ca) { ca.FlushEditActions(); // Flush any pending edits DoFormatting(mgr, span); // Format the span } }
/// <include file='doc\ViewFilter.uex' path='docs/doc[@for="ViewFilter.ReformatDocument;"]/*' /> public virtual void ReformatDocument() { if (this.CanReformat()) { Debug.Assert(this.source != null); if (this.source != null) { TextSpan span = this.source.GetDocumentSpan(); EditArray mgr = new EditArray(this.source, this.TextView, true, SR.GetString(SR.FormatSpan)); this.source.ReformatSpan(mgr, span); mgr.ApplyEdits(); } } }
private void DoFormatting(EditArray mgr, TextSpan span) { // Make sure there is one space after every comma unless followed // by a tab or comma is at end of line. IVsTextLines pBuffer = GetTextLines(); if (pBuffer != null) { List<EditSpan> changeList = AsmHighlighterFormatHelper.ReformatCode(pBuffer, span, LanguageService.GetLanguagePreferences().TabSize); if (changeList != null) { foreach (EditSpan editSpan in changeList) { // Add edit operation mgr.Add(editSpan); } } } }
private void DoFormatting(EditArray mgr, TextSpan span) { // Make sure there is one space after every comma unless followed // by a tab or comma is at end of line. IVsTextLines pBuffer = GetTextLines(); if (pBuffer != null) { // List<EditSpan> changeList = new List<EditSpan>(); // BETA DISABLED List<EditSpan> changeList = NShaderFormatHelper.ReformatCode(pBuffer, span, LanguageService.GetLanguagePreferences().TabSize); foreach (EditSpan editSpan in changeList) { // Add edit operation mgr.Add(editSpan); } // Apply all edits mgr.ApplyEdits(); } }
/// <include file='doc\ViewFilter.uex' path='docs/doc[@for="ViewFilter.ReformatSelection;"]/*' /> public virtual void ReformatSelection() { if (this.CanReformat()) { Debug.Assert(this.source != null); if (this.source != null) { TextSpan ts = GetSelection(); if (TextSpanHelper.IsEmpty(ts)) { // format just this current line. ts.iStartIndex = 0; ts.iEndLine = ts.iStartLine; ts.iEndIndex = this.source.GetLineLength(ts.iStartLine); } EditArray mgr = new EditArray(this.source, this.TextView, true, SR.GetString(SR.FormatSpan)); this.source.ReformatSpan(mgr, ts); mgr.ApplyEdits(); } } }
// ReSharper restore ParameterTypeCanBeEnumerable.Local // ReSharper disable ParameterTypeCanBeEnumerable.Local private void MakeChanges(IGrouping<FixedType.Class, MemberImplInfo>[] stubs, LanguagePreferences pref, EditArray editArray) { var newLine = Environment.NewLine; foreach (var stub in stubs) { var sb = MakeStubsForTypeMembers(stub); // На данном этапе в "sb" находится текст заглушек для членов тела которых отбиты одной табуляцией на отступ. // Заменяем этот табы на отступ указанный в настройках студии для Nemerle. // TODO: Надо сразу генерировать правлиьные отступы, а не пользоваться табами, так как отступы // могут быть не кратными размеру табуляции. При этом отступы должны дополняться пробелами. // подроности смотри в MakeIndentString(). if (!pref.InsertTabs && pref.IndentSize == 1) sb.Replace("\t", pref.MakeIndentString()); // Кроме того члены не имеют отсупа от левого края. Отступ должен совпадать с отступом // типа в который помещаются плюс один отступ. // Кроме того пользователю будет удобно если добавляемые члены будут добавлены после // последнего члена того же (т.е. типа чьи члены реализуются) типа уже имеющегося в данном типе. // Таким образом мы должны попытаться найти уже реализованные типы. В них найти самый послединй, // и вставить новые члены после него. Если в текущем типе (_ty) еще не было реализовано членов // подтипа (например, интерфейса) к которому относятся добавляемые члены, то производим вставку // в конец текущего типа. TextPoint pt; string indent; var lastImplementedMembers = NUtils.GetLastImplementedMembersOfInterface(_ty, stub.Key); #region Calc indent and insertion point if (lastImplementedMembers.IsSome) { // Используем meber.Value для получения места вставки var endLine = lastImplementedMembers.Value.Location.EndLine; var text = _source.GetLine(endLine); indent = text.GetLiadingSpaces(); pt = new TextPoint(endLine + 1, 1); //TODO: Этот код рассчитывает на то, что за членом не идет многострочного коментария // или другого члена. Надо бы сделать реализацию не закладывающуюся на это. } else // Ни одного члена этого интерфейса не реализовано в классе... { // Оборачиваем реализуемые методы в #region if (_cbGenerateRegion.Checked) { sb.Insert(0, "#region " + stub.Key + " Members" + newLine + newLine); sb.AppendLine("#endregion" + newLine); } // Вставляем описание интерфейса в конец класса var endLine = _ty.Location.EndLine; var text = _source.GetLine(endLine); indent = text.GetLiadingSpaces(); pt = new TextPoint(endLine, 1); indent += pref.MakeIndentString(); //TODO: Этот код рассчитывает на то, что конец типа распологается на отдельной строке. // Надо бы сделать реализацию не закладывающуюся на это. } #endregion sb.Insert(0, indent); sb.Replace("\n", "\n" + indent); TrimEnd(sb); var inertLoc = new Location(_source.FileIndex, pt, pt); editArray.Add(new EditSpan(inertLoc.ToTextSpan(), sb.ToString())); } }
private void InsertStabsIntoSource() { var methodStubInfos = ReadMethodStubInfosFromDataGrideView().ToArray(); var laggSrv = _source.LanguageService; var pref = laggSrv.Preferences; var sufix = methodStubInfos.Length > 1 ? "s" : ""; var editArray = new EditArray(_source, null, true, "implement interface" + sufix + " stub" + sufix); _source.LockWrite(); try { MakeChanges(methodStubInfos, pref, editArray); editArray.ApplyEdits(); Close(); } catch (Exception ex) { _source.ProjectInfo.ShowMessage("Error: " + ex.Message, MessageType.Error); } finally { editArray.Dispose(); _source.UnlockWrite(); } }
internal void ReformatSpan(EditArray mgr, TextSpan span, IFormatter provider) { var sourcePart = Data.ToSourcePart(span); var reformat = Compiler.Locate(sourcePart).Reformat(sourcePart, provider); mgr.Add(new EditSpan(span, reformat)); mgr.ApplyEdits(); }
/// <include file='doc\LanguageService.uex' path='docs/doc[@for="ViewFilter.Reformat"]/*' /> /// <summary> /// This method formats the given span using the given EditArray. The default behavior does nothing. /// So you need to override this method if you want formatting to work. /// An empty input span means reformat the entire document. /// You also need to turn on Preferences.EnableFormatSelection. /// </summary> public virtual void ReformatSpan(EditArray mgr, TextSpan span) { }
/// <summary> /// Reformat the text buffer /// </summary> void FormatBuffer(Source src) { using (EditArray edits = new EditArray(src, null, false, Resources.ReformatBuffer)) { TextSpan span = src.GetDocumentSpan(); src.ReformatSpan(edits, span); } }
/// <include file='doc\ExpansionProvider.uex' path='docs/doc[@for="ExpansionProvider.FormatSpan"]/*' /> public virtual int FormatSpan(IVsTextLines buffer, TextSpan2[] ts) { if (this.source.GetTextLines() != buffer) { throw new System.ArgumentException(SR.GetString(SR.UnknownBuffer), "buffer"); } int rc = NativeMethods.E_NOTIMPL; if (ts != null) { for (int i = 0, n = ts.Length; i < n; i++) { if (this.source.LanguageService.Preferences.EnableFormatSelection) { TextSpan span = TextSpanHelper.TextSpanFromTextSpan2(ts[i]); // We should not merge edits in this case because it might clobber the // $varname$ spans which are markers for yellow boxes. EditArray edits = new EditArray(this.source, this.view, false, SR.GetString(SR.FormatSpan)); this.source.ReformatSpan(edits, span); edits.ApplyEdits(); rc = NativeMethods.S_OK; } } } return rc; }
public override TextSpan UncommentLines(TextSpan span, string lineComment) { // Remove line comments int clen = lineComment.Length; var editMgr = new EditArray(this, null, true, "UncommentLines"); for (int line = span.iStartLine; line <= span.iEndLine; line++) { int i = this.ScanToNonWhitespaceChar(line); string text = base.GetLine(line); if ((i + clen) <= text.Length && text.Substring(i, clen) == lineComment) { var es = new EditSpan(new TextSpan() { iEndLine = line, iStartLine = line, iStartIndex = i, iEndIndex = i + clen }, ""); editMgr.Add(es); // remove line comment. if (line == span.iStartLine && span.iStartIndex != 0) span.iStartIndex = i; } } editMgr.ApplyEdits(); span.iStartIndex = 0; return span; }