연습: 코드 조각을 구현
코드 조각을 만들어 확장의 사용자가 자신의 코드를 추가할 수 있도록 확장 편집기에서 포함할 수 있습니다.
코드 조각을 코드 또는 텍스트 파일에 포함 시킬 수 있습니다 다른 조각입니다. 특정 프로그래밍 언어의 경우에 등록 되어 있는 모든 조각을 볼 수의 도구 메뉴를 클릭 코드 조각 관리자. 단편을 표시할 위치를 마우스 오른쪽 단추로 파일에 코드 조각을 삽입 합니다. 조각 삽입 또는 감싸기, 원하는 코드 조각을 찾아 두 번 클릭 합니다. TAB 키나 SHIFT + TAB 관련 부분 코드 조각 수정 하 고 다음 그대로 ENTER 키나 ESC 키를 눌러 키를 누릅니다. 자세한 내용은 코드 조각을 참조하십시오.
코드 조각은.snippet 파일 이름 확장명을 가진 XML 파일에 포함 되어 있습니다. 코드 조각을 사용자 찾기 및 변경할 수 있도록 코드 조각이 삽입 된 후에 강조 표시 된 필드를 포함할 수 있습니다. 코드 조각 파일에 대 한 정보도 제공의 코드 조각 관리자 올바른 범주에서 조각 이름을 표시할 수 있도록 합니다. 코드 조각 스키마 정보에 대 한 자세한 내용은 코드 조각 스키마 참조.
이 연습에서는 이러한 작업을 수행 하는 방법에 설명 합니다.
만들기 및 특정 언어에 대 한 코드 조각 등록.
추가 조각 삽입 명령에 바로 가기 메뉴입니다.
조각 확장을 구현 합니다.
이 연습에 기초한 연습: 문 완성 표시.
사전 요구 사항
이 연습을 완료 하려면 설치 해야 해당 Visual Studio 2010 SDK. Visual Studio SDK, 및 다운로드에 대 한 내용은 Visual Studio 확장성 개발자 센터 MSDN 웹 사이트에서.
만들기 및 코드 단편 등록
일반적으로 코드 조각에 등록 된 언어 서비스와 관련 됩니다. 그러나 구현할 필요가 없습니다를 LanguageService 코드 조각 등록 합니다. 대신 방금 조각 인덱스 파일의 GUID를 지정 하 고 다음에 동일한 GUID를 사용 하는 ProvideLanguageCodeExpansionAttribute 프로젝트에 추가 합니다.
다음 단계는 코드 조각을 만들어 특정 GUID와 연결 하는 방법을 보여 줍니다.
코드 조각을 만들려면
다음과 같은 디렉터리 구조를 만듭니다.
%InstallDir%\TestSnippets\Snippets\1033\
위치 되었습니다 % % Visual Studio 설치 폴더입니다. (코드 조각을 설치 하려면 일반적으로이 경로 사용 하지만 모든 경로 지정할 수 있습니다.)
\1033\ 폴더에서.xml 파일을 만들고 이름을 SnippetIndex.xml. (이 이름은 일반적으로 조각 색인 파일을 사용 하지만가.xml 파일 이름 확장명으로 사용자 이름을 지정할 수 있습니다.) 다음 텍스트를 추가 GUID 자리 표시자를 삭제 및 직접 추가 합니다.
<?xml version="1.0" encoding="utf-8" ?> <SnippetCollection> <Language Lang="TestSnippets" Guid="{00000000-0000-0000-0000-000000000000}"> <SnippetDir> <OnOff>On</OnOff> <Installed>true</Installed> <Locale>1033</Locale> <DirPath>%InstallRoot%\TestSnippets\Snippets\%LCID%\</DirPath> <LocalizedName>Snippets</LocalizedName> </SnippetDir> </Language> </SnippetCollection>
코드 조각 폴더에 파일을 작성 하 고 테스트 이름을.snippet를 하 고 다음 텍스트를 추가 합니다.
<?xml version="1.0" encoding="utf-8" ?> <CodeSnippets xmlns="https://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"> <CodeSnippet Format="1.0.0"> <Header> <Title>Test replacement fields</Title> <Shortcut>test</Shortcut> <Description>Code snippet for testing replacement fields</Description> <Author>MSIT</Author> <SnippetTypes> <SnippetType>Expansion</SnippetType> </SnippetTypes> </Header> <Snippet> <Declarations> <Literal> <ID>param1</ID> <ToolTip>First field</ToolTip> <Default>first</Default> </Literal> <Literal> <ID>param2</ID> <ToolTip>Second field</ToolTip> <Default>second</Default> </Literal> </Declarations> <References> <Reference> <Assembly>System.Windows.Forms.dll</Assembly> </Reference> </References> <Code Language="TestSnippets"> <![CDATA[MessageBox.Show("$param1$"); MessageBox.Show("$param2$");]]> </Code> </Snippet> </CodeSnippet> </CodeSnippets>
다음 단계 코드 조각 등록 하는 방법을 보여 줍니다.
코드 조각에 대 한 특정 GUID 등록할 수
CompletionTest 프로젝트를 엽니다. 이 프로젝트를 만드는 방법에 대 한 자세한 내용은 연습: 문 완성 표시.
프로젝트에서 다음 어셈블리에 대 한 참조를 추가 합니다.
Microsoft.VisualStudio.TextManager.Interop
Microsoft.VisualStudio.TextManager.Interop.8.0
microsoft.msxml
코드 조각 등록 하려면 프로젝트.pkgdef 파일을 출력 해야 합니다. 자세한 내용은 Registering VSPackages를 참조하십시오.
프로젝트의 source.extension.vsixmanifest 파일을 엽니다.
에 콘텐츠 섹션에서 클릭 추가 콘텐츠선택의 VS 패키지 콘텐츠 형식 선택의 프로젝트 옵션을 선택 하 고 TestCompletion 드롭다운 목록에서.
다음 줄은 파일에 나타나야 합니다.
TestCompletion;PkgdefProjectOutputGroup|
Source.extension.vsixmanifest 파일을 저장 하 고 닫습니다.
추가 정적 SnippetUtilities 클래스를 프로젝트에 있습니다.
Module SnippetUtilities
static class SnippetUtilities
SnippetUtilities 클래스의 GUID를 정의 하 고 얼른 SnippetsIndex.xml 파일에 사용 되는 값입니다.
Friend Const LanguageServiceGuidStr As String = "00000000-0000-0000-0000-00000000"
internal const string LanguageServiceGuidStr = "00000000-0000-0000-0000-00000000";
추가 ProvideLanguageCodeExpansionAttribute 에 있는 TestCompletionHandler 클래스입니다. 프로젝트의 공용 또는 내부 (비정적) 클래스에이 특성을 추가할 수 있습니다. (추가 할 수 있습니다는 using Microsoft.VisualStudio.Shell 네임 스페이스에 대 한 문입니다.)
<ProvideLanguageCodeExpansion( SnippetUtilities.LanguageServiceGuidStr, "TestSnippets", 0, "TestSnippets", "%InstallRoot%\TestSnippets\Snippets\%LCID%\SnippetsIndex.xml", SearchPaths:="%InstallRoot%\TestSnippets\Snippets\%LCID%\", ForceCreateDirs:="%InstallRoot%\TestSnippets\Snippets\%LCID%\")> Friend Class TestCompletionCommandHandler Implements IOleCommandTarget
[ProvideLanguageCodeExpansion( SnippetUtilities.LanguageServiceGuidStr, "TestSnippets", //the language name 0, //the resource id of the language "TestSnippets", //the language ID used in the .snippet files @"%InstallRoot%\TestSnippets\Snippets\%LCID%\SnippetsIndex.xml", //the path of the index file SearchPaths = @"%InstallRoot%\TestSnippets\Snippets\%LCID%\", ForceCreateDirs = @"%InstallRoot%\TestSnippets\Snippets\%LCID%\")] internal class TestCompletionCommandHandler : IOleCommandTarget
프로젝트를 빌드하고 실행합니다. 실험적인 프로젝트가 실행 될 때 시작 되는 Visual Studio 인스턴스에서 방금 등록 코드 조각에 표시 되어야의 코드 조각 관리자 아래는 TestSnippets 언어.
코드 조각 삽입 명령을 바로 가기 메뉴에 추가
조각 삽입 명령 텍스트 파일에 대 한 바로 가기 메뉴에 포함 됩니다. 따라서 명령을 사용 하도록 설정 해야 합니다.
코드 조각 삽입 명령을 바로 가기 메뉴를 추가 하려면
열려 있는 TestCompletionCommandHandler 클래스 파일입니다.
이 클래스를 구현 하 고 있기 때문에 IOleCommandTarget, 활성화할 수는 조각 삽입 명령에 QueryStatus 메서드. 명령을 사용 하려면 먼저이 메서드는 자동화 함수 안에서 때문에 호출 되 고 되지 않습니다 것을 확인 하면는 조각 삽입 명령을 클릭 하 고 코드 조각 선택을 사용자 인터페이스 (UI)를 표시 합니다.
Public Function QueryStatus(ByRef pguidCmdGroup As Guid, ByVal cCmds As UInteger, ByVal prgCmds As OLECMD(), ByVal pCmdText As IntPtr) As Integer Implements IOleCommandTarget.QueryStatus If Not VsShellUtilities.IsInAutomationFunction(m_provider.ServiceProvider) Then If pguidCmdGroup = VSConstants.VSStd2K AndAlso cCmds > 0 Then ' make the Insert Snippet command appear on the context menu If CUInt(prgCmds(0).cmdID) = CUInt(VSConstants.VSStd2KCmdID.INSERTSNIPPET) Then prgCmds(0).cmdf = CInt(Constants.MSOCMDF_ENABLED) Or CInt(Constants.MSOCMDF_SUPPORTED) Return VSConstants.S_OK End If End If End If Return m_nextCommandHandler.QueryStatus(pguidCmdGroup, cCmds, prgCmds, pCmdText) End Function
public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText) { if (!VsShellUtilities.IsInAutomationFunction(m_provider.ServiceProvider)) { if (pguidCmdGroup == VSConstants.VSStd2K && cCmds > 0) { // make the Insert Snippet command appear on the context menu if ((uint)prgCmds[0].cmdID == (uint)VSConstants.VSStd2KCmdID.INSERTSNIPPET) { prgCmds[0].cmdf = (int)Constants.MSOCMDF_ENABLED | (int)Constants.MSOCMDF_SUPPORTED; return VSConstants.S_OK; } } } return m_nextCommandHandler.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText); }
프로젝트를 빌드하고 실행합니다. 실험 인스턴스,.zzz 파일 이름 확장명을 가진 파일을 열고에 마우스. 조각 삽입 명령을 바로 가기 메뉴에서 표시 되어야 합니다.
코드 조각 선택 UI에 조각 확장 구현
이 섹션에서는 코드 조각 확장 있도록 조각 선택 UI를 구현 하는 방법을 보여 줍니다 때 표시 조각 삽입 바로 가기 메뉴에서 클릭할. 코드 조각은 사용자 코드 조각의 바로 가기를 입력 한 다음 탭을 누를 때에 확장 됩니다.
조각 선택 UI를 표시 하려면 탐색 및 수용 post-insertion 조각 사용 하 고, 해당 Exec 메서드. 에 삽입 된 처리는 OnItemChosen 메서드.
레거시 코드 조각 확장 구현을 사용 Microsoft.VisualStudio.TextManager.Interop 인터페이스입니다. 현재 편집기 클래스에서의 레거시 코드로 변환 하는 경우 레거시 인터페이스 줄 번호 및 열 번호의 조합을 사용 하 여 텍스트 버퍼에 위치를 지정할 수 있지만 클래스는 현재 하나의 인덱스만 사용. 따라서 버퍼는 각각 10 개의 문자가 있는 세 줄 (1 문자 수를 계산 하는 줄 바꿈)가, 세 번째 줄에서 네 번째 문자 27 위치는 현재 구현 이지만 2 줄 3 이전 구현에 배치 합니다.
조각 확장을 구현.
포함 된 파일에는 TestCompletionCommandHandler 클래스, 다음 추가 using 문.
Imports Microsoft.VisualStudio.Text.Operations Imports MSXML
using Microsoft.VisualStudio.Text.Operations; using MSXML; using System.ComponentModel.Composition;
확인은 TestCompletionCommandHandler 클래스 구현에서 IVsExpansionClient 인터페이스.
<ProvideLanguageCodeExpansion( SnippetUtilities.LanguageServiceGuidStr, "TestSnippets", 0, "TestSnippets", "%InstallRoot%\TestSnippets\Snippets\%LCID%\SnippetsIndex.xml", SearchPaths:="%InstallRoot%\TestSnippets\Snippets\%LCID%\", ForceCreateDirs:="%InstallRoot%\TestSnippets\Snippets\%LCID%\")> Friend Class TestCompletionCommandHandler Implements IOleCommandTarget Implements IVsExpansionClient
internal class TestCompletionCommandHandler : IOleCommandTarget, IVsExpansionClient
에 TestCompletionCommandHandlerProvider 클래스, 가져오기의 ITextStructureNavigatorSelectorService.
<Import()> Friend Property NavigatorService As ITextStructureNavigatorSelectorService
[Import] internal ITextStructureNavigatorSelectorService NavigatorService { get; set; }
일부 코드 확장 인터페이스에 대 한 private 필드를 추가 하는 IVsTextView.
Dim m_vsTextView As IVsTextView Dim m_exManager As IVsExpansionManager Dim m_exSession As IVsExpansionSession
IVsTextView m_vsTextView; IVsExpansionManager m_exManager; IVsExpansionSession m_exSession;
생성자에는 TestCompletionCommandHandler 클래스, 다음 필드를 설정 합니다.
Friend Sub New(ByVal textViewAdapter As IVsTextView, ByVal textView As ITextView, ByVal provider As TestCompletionHandlerProvider) Me.m_textView = textView Me.m_provider = provider Me.m_vsTextView = textViewAdapter Dim textManager As IVsTextManager2 = DirectCast(m_provider.ServiceProvider.GetService(GetType(SVsTextManager)), IVsTextManager2) textManager.GetExpansionManager(m_exManager) m_exSession = Nothing 'add the command to the command chain textViewAdapter.AddCommandFilter(Me, m_nextCommandHandler) End Sub
internal TestCompletionCommandHandler(IVsTextView textViewAdapter, ITextView textView, TestCompletionHandlerProvider provider) { this.m_textView = textView; m_vsTextView = textViewAdapter; m_provider = provider; //get the text manager from the service provider IVsTextManager2 textManager = (IVsTextManager2)m_provider.ServiceProvider.GetService(typeof(SVsTextManager)); textManager.GetExpansionManager(out m_exManager); m_exSession = null; //add the command to the command chain textViewAdapter.AddCommandFilter(this, out m_nextCommandHandler); }
클릭할 때 코드 조각 선택을 표시 하는 조각 삽입 명령, 다음 코드를 추가 Exec 메서드. (이 설명을 쉽게 읽을 수 있도록 문 완성 기능을 사용 하는 exec () 코드 표시 되지 않습니다. 대신 코드 블록을 기존 메서드를 추가 합니다.) 다음 코드 블록을 문자를 검사 하는 코드 뒤에 추가 합니다.
'code previously written for Exec If pguidCmdGroup = VSConstants.VSStd2K AndAlso nCmdID = CUInt(VSConstants.VSStd2KCmdID.TYPECHAR) Then typedChar = ChrW(CUShort(Marshal.GetObjectForNativeVariant(pvaIn))) End If 'the snippet picker code starts here If nCmdID = CUInt(VSConstants.VSStd2KCmdID.INSERTSNIPPET) Then Dim textManager As IVsTextManager2 = DirectCast(m_provider.ServiceProvider.GetService(GetType(SVsTextManager)), IVsTextManager2) textManager.GetExpansionManager(m_exManager) m_exManager.InvokeInsertionUI( m_vsTextView, Me, New Guid(SnippetUtilities.LanguageServiceGuidStr), Nothing, 0, 0, Nothing, 0, 0, "TestSnippets", String.Empty) Return VSConstants.S_OK End If
//code previously written for Exec if (pguidCmdGroup == VSConstants.VSStd2K && nCmdID == (uint)VSConstants.VSStd2KCmdID.TYPECHAR) { typedChar = (char)(ushort)Marshal.GetObjectForNativeVariant(pvaIn); } //the snippet picker code starts here if (nCmdID == (uint)VSConstants.VSStd2KCmdID.INSERTSNIPPET) { IVsTextManager2 textManager = (IVsTextManager2)m_provider.ServiceProvider.GetService(typeof(SVsTextManager)); textManager.GetExpansionManager(out m_exManager); m_exManager.InvokeInsertionUI( m_vsTextView, this, //the expansion client new Guid(SnippetUtilities.LanguageServiceGuidStr), null, //use all snippet types 0, //number of types (0 for all) 0, //ignored if iCountTypes == 0 null, //use all snippet kinds 0, //use all snippet kinds 0, //ignored if iCountTypes == 0 "TestSnippets", //the text to show in the prompt string.Empty); //only the ENTER key causes insert return VSConstants.S_OK; }
코드 조각을 탐색할 수 있는 필드가 있는 경우 확장 명시적으로 인정 되는 때까지 확장 세션이 열려 보관 됩니다. 코드 조각에 필드가 없으면 세션이 닫히고로 반환 null 가 InvokeInsertionUI 메서드. 에 Exec 메서드를 조각 선택 UI 코드는 이전 단계에서 추가한 후 추가 (TAB 키나 SHIFT + TAB 코드 단편 삽입 후 누를 때) 조각 탐색을 처리 하는 다음 코드입니다.
'the expansion insertion is handled in OnItemChosen 'if the expansion session is still active, handle tab/backtab/return/cancel If m_exSession IsNot Nothing Then If nCmdID = CUInt(VSConstants.VSStd2KCmdID.BACKTAB) Then m_exSession.GoToPreviousExpansionField() Return VSConstants.S_OK ElseIf nCmdID = CUInt(VSConstants.VSStd2KCmdID.TAB) Then m_exSession.GoToNextExpansionField(0) 'false to support cycling through all the fields Return VSConstants.S_OK ElseIf nCmdID = CUInt(VSConstants.VSStd2KCmdID.[RETURN]) OrElse nCmdID = CUInt(VSConstants.VSStd2KCmdID.CANCEL) Then If m_exSession.EndCurrentExpansion(0) = VSConstants.S_OK Then m_exSession = Nothing Return VSConstants.S_OK End If End If End If
//the expansion insertion is handled in OnItemChosen //if the expansion session is still active, handle tab/backtab/return/cancel if (m_exSession != null) { if (nCmdID == (uint)VSConstants.VSStd2KCmdID.BACKTAB) { m_exSession.GoToPreviousExpansionField(); return VSConstants.S_OK; } else if (nCmdID == (uint)VSConstants.VSStd2KCmdID.TAB) { m_exSession.GoToNextExpansionField(0); //false to support cycling through all the fields return VSConstants.S_OK; } else if (nCmdID == (uint)VSConstants.VSStd2KCmdID.RETURN || nCmdID == (uint)VSConstants.VSStd2KCmdID.CANCEL) { if (m_exSession.EndCurrentExpansion(0) == VSConstants.S_OK) { m_exSession = null; return VSConstants.S_OK; } } }
사용자는 해당 바로 가기를 입력 하 고 다음 탭을 누를 때 코드 조각을 삽입 하려면 코드에 추가 Exec 메서드. 코드 조각을 삽입 하는 private 메서드를 나중에 표시 됩니다. 후 이전 단계에서 추가한 탐색 코드 다음 코드를 추가 합니다.
'neither an expansion session nor a completion session is open, but we got a tab, so check whether the last word typed is a snippet shortcut If m_session Is Nothing AndAlso m_exSession Is Nothing AndAlso nCmdID = CUInt(VSConstants.VSStd2KCmdID.TAB) Then 'get the word that was just added Dim pos As CaretPosition = m_textView.Caret.Position Dim word As TextExtent = m_provider.NavigatorService.GetTextStructureNavigator(m_textView.TextBuffer).GetExtentOfWord(pos.BufferPosition - 1) Dim textString As String = word.Span.GetText() 'if it is a code snippet, insert it, otherwise carry on If InsertAnyExpansion(textString, Nothing, Nothing) Then Return VSConstants.S_OK End If End If
//neither an expansion session nor a completion session is open, but we got a tab, so check whether the last word typed is a snippet shortcut if (m_session == null && m_exSession == null && nCmdID == (uint)VSConstants.VSStd2KCmdID.TAB) { //get the word that was just added CaretPosition pos = m_textView.Caret.Position; TextExtent word = m_provider.NavigatorService.GetTextStructureNavigator(m_textView.TextBuffer).GetExtentOfWord(pos.BufferPosition - 1); //use the position 1 space back string textString = word.Span.GetText(); //the word that was just added //if it is a code snippet, insert it, otherwise carry on if (InsertAnyExpansion(textString, null, null)) return VSConstants.S_OK; }
메서드를 구현에서 IVsExpansionClient 인터페이스입니다. 이 구현에서 관심 분야의 유일한 메서드는 EndExpansion 및 OnItemChosen. 다른 메서드는 바로 반환 해야 S_OK.
Public Function EndExpansion() As Integer Implements IVsExpansionClient.EndExpansion m_exSession = Nothing Return VSConstants.S_OK End Function Public Function FormatSpan(ByVal pBuffer As IVsTextLines, ByVal ts As TextSpan()) As Integer Implements IVsExpansionClient.FormatSpan Return VSConstants.S_OK End Function Public Function GetExpansionFunction(ByVal xmlFunctionNode As IXMLDOMNode, ByVal bstrFieldName As String, ByRef pFunc As IVsExpansionFunction) As Integer Implements IVsExpansionClient.GetExpansionFunction pFunc = Nothing Return VSConstants.S_OK End Function Public Function IsValidKind(ByVal pBuffer As IVsTextLines, ByVal ts As TextSpan(), ByVal bstrKind As String, ByRef pfIsValidKind As Integer) As Integer Implements IVsExpansionClient.IsValidKind pfIsValidKind = 1 Return VSConstants.S_OK End Function Public Function IsValidType(ByVal pBuffer As IVsTextLines, ByVal ts() As TextSpan, ByVal rgTypes() As String, ByVal iCountTypes As Integer, ByRef pfIsValidType As Integer) As Integer Implements IVsExpansionClient.IsValidType pfIsValidType = 1 Return VSConstants.S_OK End Function Public Function OnAfterInsertion(ByVal pSession As IVsExpansionSession) As Integer Implements IVsExpansionClient.OnAfterInsertion Return VSConstants.S_OK End Function Public Function OnBeforeInsertion(ByVal pSession As IVsExpansionSession) As Integer Implements IVsExpansionClient.OnBeforeInsertion Return VSConstants.S_OK End Function Public Function PositionCaretForEditing(ByVal pBuffer As IVsTextLines, ByVal ts As TextSpan()) As Integer Implements IVsExpansionClient.PositionCaretForEditing Return VSConstants.S_OK End Function
public int EndExpansion() { m_exSession = null; return VSConstants.S_OK; } public int FormatSpan(IVsTextLines pBuffer, TextSpan[] ts) { return VSConstants.S_OK; } public int GetExpansionFunction(IXMLDOMNode xmlFunctionNode, string bstrFieldName, out IVsExpansionFunction pFunc) { pFunc = null; return VSConstants.S_OK; } public int IsValidKind(IVsTextLines pBuffer, TextSpan[] ts, string bstrKind, out int pfIsValidKind) { pfIsValidKind = 1; return VSConstants.S_OK; } public int IsValidType(IVsTextLines pBuffer, TextSpan[] ts, string[] rgTypes, int iCountTypes, out int pfIsValidType) { pfIsValidType = 1; return VSConstants.S_OK; } public int OnAfterInsertion(IVsExpansionSession pSession) { return VSConstants.S_OK; } public int OnBeforeInsertion(IVsExpansionSession pSession) { return VSConstants.S_OK; } public int PositionCaretForEditing(IVsTextLines pBuffer, TextSpan[] ts) { return VSConstants.S_OK; }
OnItemChosen 메서드를 구현합니다. 나중에 실제로 삽입 하는 확장 하는 도우미 메서드를 설명 합니다. TextSpan 에서 액세스할 수 있는 행 및 열 정보 제공의 IVsTextView.
Public Function OnItemChosen(ByVal pszTitle As String, ByVal pszPath As String) As Integer Implements IVsExpansionClient.OnItemChosen InsertAnyExpansion(Nothing, pszTitle, pszPath) Return VSConstants.S_OK End Function
public int OnItemChosen(string pszTitle, string pszPath) { InsertAnyExpansion(null, pszTitle, pszPath); return VSConstants.S_OK; }
코드 조각 바로 가기 또는 제목 및 경로에 따라 다음 개인 메서드를 삽입 합니다. 그런 다음 호출에서 InsertNamedExpansion 메서드로 코드 조각.
Private Function InsertAnyExpansion(ByVal shortcut As String, ByVal title As String, ByVal path As String) As Boolean Dim endColumn As Integer, startLine As Integer 'get the column number from the IVsTextView, not the ITextView m_vsTextView.GetCaretPos(startLine, endColumn) Dim addSpan As New TextSpan() addSpan.iStartIndex = endColumn addSpan.iEndIndex = endColumn addSpan.iStartLine = startLine addSpan.iEndLine = startLine 'get the expansion from the shortcut If shortcut IsNot Nothing Then 'reset the TextSpan to the width of the shortcut, because we're going to replace the shortcut with the expansion addSpan.iStartIndex = addSpan.iEndIndex - shortcut.Length m_exManager.GetExpansionByShortcut( Me, New Guid(SnippetUtilities.LanguageServiceGuidStr), shortcut, m_vsTextView, New TextSpan() {addSpan}, 0, path, title) End If If title IsNot Nothing AndAlso path IsNot Nothing Then Dim textLines As IVsTextLines = Nothing m_vsTextView.GetBuffer(textLines) Dim bufferExpansion As IVsExpansion = DirectCast(textLines, IVsExpansion) If bufferExpansion IsNot Nothing Then Dim hr As Integer = bufferExpansion.InsertNamedExpansion( title, path, addSpan, Me, New Guid(SnippetUtilities.LanguageServiceGuidStr), 0, m_exSession) If VSConstants.S_OK = hr Then Return True End If End If End If Return False End Function
private bool InsertAnyExpansion(string shortcut, string title, string path) { //first get the location of the caret, and set up a TextSpan int endColumn, startLine; //get the column number from the IVsTextView, not the ITextView m_vsTextView.GetCaretPos(out startLine, out endColumn); TextSpan addSpan = new TextSpan(); addSpan.iStartIndex = endColumn; addSpan.iEndIndex = endColumn; addSpan.iStartLine = startLine; addSpan.iEndLine = startLine; if (shortcut != null) //get the expansion from the shortcut { //reset the TextSpan to the width of the shortcut, //because we're going to replace the shortcut with the expansion addSpan.iStartIndex = addSpan.iEndIndex - shortcut.Length; m_exManager.GetExpansionByShortcut( this, new Guid(SnippetUtilities.LanguageServiceGuidStr), shortcut, m_vsTextView, new TextSpan[] { addSpan }, 0, out path, out title); } if (title != null && path != null) { IVsTextLines textLines; m_vsTextView.GetBuffer(out textLines); IVsExpansion bufferExpansion = (IVsExpansion)textLines; if (bufferExpansion != null) { int hr = bufferExpansion.InsertNamedExpansion( title, path, addSpan, this, new Guid(SnippetUtilities.LanguageServiceGuidStr), 0, out m_exSession); if (VSConstants.S_OK == hr) { return true; } } } return false; }
빌드 및 테스트 코드 확장
조각 확장 프로젝트에 사용할 수 있는지 여부를 테스트할 수 있습니다.
빌드 및 테스트 코드 조각 확장 하기
솔루션을 빌드합니다. 이 프로젝트를 디버거에서 실행할 때 Visual Studio 두 번째 인스턴스를 인스턴스화합니다.
텍스트 파일을 열고 일부 텍스트를 입력 합니다.
어딘가에에서 텍스트를 마우스 오른쪽 단추로 누르고 조각 삽입.
조각 선택 UI 표시 하 고 문자열 "테스트 대체 필드"를 표시 해야 합니다. 이 문자열을 두 번 클릭 합니다.
다음 코드를 삽입 해야 합니다.
MessageBox.Show("first"); MessageBox.Show("second");
Enter 키 또는 esc 키를 누르지 마십시오.
전환 탭 및 SHIFT + TAB 키를 눌러 "1"과 "2" 사이입니다.
Esc 키 또는 ENTER 키를 눌러 삽입을 적용 합니다.
텍스트의 다른 부분에서 "test"를 입력 한 다음 TAB 키를 누릅니다. 코드 조각은 코드 조각 바로 가기 "테스트" 이기 때문에 다시 삽입 해야 합니다.