2011-01-13 123 views
1

我試圖創建一個新的宏,它將當前選定的文本並在其周圍放置大括號(在製作換行符後),而當然,根據需要縮進。適用於Visual Studio的「新範圍」宏

因此,舉例來說,如果用戶選擇的代碼x = 0;並運行下面的代碼的宏:

if (x != 0) x = 0; 

應該變成:

if (x != 0) 
{ 
    x = 0; 
} 

(片段不幫在這裏,因爲這也需要爲不支持的源代碼工作。)

有人能幫我弄清楚如何正確地執行縮進和換行符嗎?這是我的:

Public Sub NewScope() 
    Dim textDoc As TextDocument = _ 
       CType(DTE.ActiveDocument.Object("TextDocument"), TextDocument) 
    textDoc.??? 
End Sub 

但我怎麼弄出目前的縮進和換行?

+0

...真的嗎?我不敢相信我有這樣的風滾草徽章,大聲笑......它似乎相當簡單。希望賞金幫助。 :) – Mehrdad 2011-01-21 22:23:13

+0

我知道這並不回答你的問題,但與Resharper,萬一有人想知道 - 這是通過Ctrl + E + U,7(環繞與{}) – 2011-01-27 23:12:58

回答

2
Sub BracketAndIndent() 
    Dim selection = CType(DTE.ActiveDocument.Selection, TextSelection) 

    ' here's the text we want to insert 
    Dim text As String = selection.Text 

    ' bracket the selection; 
    selection.Delete() 

    ' remember where we start 
    Dim start As Integer = selection.ActivePoint.AbsoluteCharOffset 

    selection.NewLine() 
    selection.Text = "{" 
    selection.NewLine() 
    selection.Insert(text) 
    selection.NewLine() 
    selection.Text = "}" 

    ' this is the position after the bracket 
    Dim endPos As Integer = selection.ActivePoint.AbsoluteCharOffset 

    ' select the whole thing, including the brackets 
    selection.CharLeft(True, endPos - start) 

    ' reformat the selection according to the language's rules 
    DTE.ExecuteCommand("Edit.FormatSelection") 
End Sub 
0

textDoc.Selection.Text = 「\ N {\ n \ t」 的+ textDoc.Selection.Text + 「\ N} \ n」 個

當然所述的\噸量前的{和}和選擇取決於當前的縮進。

由於所選文本和文檔數據存在差異,因此很難找出光標在文檔數據中的位置(至少在Outlook中是這樣)。

我想出瞭如何在Outlook中執行此操作的唯一方法是實際向後移動選擇內容,直到獲得我需要的文本,但這會導致不良效果。

嘗試選擇開始,並在文檔文本中使用該位置,查看該行並獲取標籤數量。

我想不會在VStudio中格式化字符。

+0

這個問題字面上指出,「*怎麼做我找出當前的縮進並製作一個換行符*「?對不起,但你的回答並沒有真正告訴我如何找出當前的縮進並使換行符縮進相同的數量。 :( – Mehrdad 2011-01-24 22:13:09