protected override string GetValue(Snippet snippet)
        {
            if (snippet == null)
                throw new ArgumentNullException(nameof(snippet));

            return snippet.Title;
        }
        /// <summary>
        /// Validates literals of the specified <see cref="Snippet"/>.
        /// </summary>
        /// <param name="snippet">A snippet to be validated.</param>
        /// <returns>Enumerable collection of validation results.</returns>
        public override IEnumerable<SnippetValidationResult> Validate(Snippet snippet)
        {
            if (snippet == null)
                throw new ArgumentNullException(nameof(snippet));

            foreach (Literal literal in snippet.Literals)
            {
                if (string.IsNullOrEmpty(literal.Identifier))
                {
                    yield return new SnippetValidationResult(
                        snippet,
                        ErrorCode.MissingLiteralIdentifier,
                        "Snippet literal identifier is missing.",
                        ResultImportance.Error,
                        literal);
                }
                else if (!snippet.Placeholders.Contains(literal.Identifier))
                {
                    yield return new SnippetValidationResult(
                        snippet,
                        ErrorCode.LiteralWithoutPlaceholder,
                        "Snippet literal does not have corresponding placeholder in code.",
                        ResultImportance.Error,
                        literal);
                }

                if (!ValidationHelper.IsValidLiteralIdentifier(literal.Identifier))
                {
                    yield return new SnippetValidationResult(
                        snippet,
                        ErrorCode.InvalidLiteralIdentifier,
                        "Snippet literal identifier is invalid.",
                        ResultImportance.Error,
                        literal);
                }

                if (string.IsNullOrEmpty(literal.DefaultValue))
                {
                    yield return new SnippetValidationResult(
                        snippet,
                        ErrorCode.MissingLiteralDefault,
                        "Snippet literal default value is missing.",
                        ResultImportance.Error,
                        literal);
                }
            }

            foreach (IGrouping<string, Literal> grp in snippet.Literals.GroupBy(f => f.Identifier, _stringComparer))
            {
                if (grp.CountExceeds(1))
                {
                    yield return new SnippetValidationResult(
                        snippet,
                        ErrorCode.LiteralIdentifierDuplicate,
                        $"Snippet literal identifier '{grp.Key}' is duplicated.",
                        ResultImportance.Warning);
                }
            }
        }
Example #3
0
 /// <summary>
 /// Finds the parameters in a snippet.
 /// </summary>
 /// <param name="snippet">The snippet.</param>
 /// <returns>The parameter names.</returns>
 public static string[] ExtractParameterNames(Snippet snippet)
 {
     List<string> parms = new List<string>();
     foreach(Match m in ParametersRegex.Matches(snippet.Content)) {
         string value = m.Value.Substring(1, m.Value.Length - 2);
         if(m.Success && !parms.Contains(value)) parms.Add(value);
     }
     return parms.ToArray();
 }
        /// <summary>
        /// Validates the specified <see cref="Snippet"/> according the the code snippet schema.
        /// </summary>
        /// <param name="snippet">A <see cref="Snippet"/> that is being validated.</param>
        /// <returns>A <see cref="SnippetValidationContext"/> that stores data about the validation.</returns>
        public IEnumerable<SnippetValidationResult> Validate(Snippet snippet)
        {
            if (snippet == null)
                throw new ArgumentNullException(nameof(snippet));

            var context = new SnippetValidationContext(snippet);

            foreach (SnippetValidationResult result in Validate(context))
                yield return result;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SnippetValidationResult"/> class using the specified snippet, code, description, importance and content.
        /// </summary>
        /// <param name="snippet">A snippet.</param>
        /// <param name="code">Alphanumeric code the identifies the result.</param>
        /// <param name="description">Result description.</param>
        /// <param name="importance">Result importance.</param>
        /// <param name="content">Additional result content. The value can be <c>null</c>.</param>
        /// <exception cref="ArgumentNullException"><paramref name="snippet"/> is <c>null</c>.</exception>
        public SnippetValidationResult(Snippet snippet, string code, string description, ResultImportance importance, object content)
        {
            if (snippet == null)
                throw new ArgumentNullException(nameof(snippet));

            Snippet = snippet;
            Code = code;
            Description = description;
            Importance = importance;
            Content = content;
        }
Example #6
0
        public SnippetButton(Snippet snippet, Action<Snippet> onClick)
        {
            InitializeComponent();

            SnippetName.Text = snippet.Name;
            Trigger.Text = snippet.Trigger;

            ToolTip = new SnippetTooltip(snippet);
            ToolTipService.SetPlacement(this, PlacementMode.Left);

            SnippetBtn.Click += (s, e) => onClick(snippet);
        }
        public SnippetViewModel(Snippet snippet)
        {
            if(snippet == null)
                return;

            CreatedBy = snippet.CreatedBy;
            DateCreated = snippet.DateCreated;
            Key = snippet.Key;
            Model = snippet.Model;
            Title = snippet.Title;
            View = snippet.View;
            Notes = snippet.Notes;
            Revision = snippet.Revision;
        }
        public void CompileExecutable_ValidSyntax_CompilesExecutable()
        {
            var snippet = new Snippet
            {
                Code = "Console.WriteLine(\"Hello World\");"
            };
            snippet.References.Add("System.dll");
            snippet.Imports.Add("System");

            var compiler = new CSharpSnippetCompiler("output");
            var results = compiler.CompileExecutable(snippet);

            Assert.That(results.Errors.Count == 0, results.Errors.GetDisplayString());
        }
        /// <summary>
        /// Validates a description of the specified <see cref="Snippet"/>.
        /// </summary>
        /// <param name="snippet">A snippet to be validated.</param>
        /// <returns>Enumerable collection of validation results.</returns>
        public override IEnumerable<SnippetValidationResult> Validate(Snippet snippet)
        {
            if (snippet == null)
                throw new ArgumentNullException(nameof(snippet));

            if (string.IsNullOrEmpty(snippet.Description))
            {
                yield return new SnippetValidationResult(
                    snippet,
                    ErrorCode.MissingDescription,
                    "Snippet description is missing.",
                    ResultImportance.Information);
            }
        }
        /// <summary>
        /// Validates a format version of the specified <see cref="Snippet"/>.
        /// </summary>
        /// <param name="snippet">A snippet to be validated.</param>
        /// <returns>Enumerable collection of validation results.</returns>
        public override IEnumerable<SnippetValidationResult> Validate(Snippet snippet)
        {
            if (snippet == null)
                throw new ArgumentNullException(nameof(snippet));

            if (snippet.SnippetTypes == SnippetTypes.None)
            {
                yield return new SnippetValidationResult(
                    snippet,
                    ErrorCode.MissingSnippetType,
                    "Snippet type is missing.",
                    ResultImportance.Information);
            }
        }
Example #11
0
		private void SetupTestDefaults()
		{
			snippet = new Snippet()
			          	{
			          		View = @"@{ 
										var Now = DateTime.Now.ToString(); 
									 }
									 <h1>Basic Integration Test</h1>
									 Test performed at: @Now
									",
			          		Title = "Basic Integration Test",
			          		Notes = "Having a meaningful note helps you in remembering things in future.",
			          		CreatedBy = "Anonymous",
			          		Revision = 0,
			          	};
		}
Example #12
0
		private static OracleCodeSnippet BuildCodeSnippet(Snippet s, SourcePosition sourcePosition)
		{
			return new OracleCodeSnippet
			{
				Name = s.Name,
				BaseText = s.Text,
				Description = s.Description,
				SourceToReplace = sourcePosition,
				Parameters = new List<ICodeSnippetParameter>(
					(s.Parameters ?? Enumerable.Empty<SnippetParameter>()).Select(p => new OracleCodeSnippetParameter
					{
						Index = p.Index,
						DefaultValue = p.DefaultValue
					})).AsReadOnly()
			};
		}
        /// <summary>
        /// Validates namespaces of the specified <see cref="Snippet"/>.
        /// </summary>
        /// <param name="snippet">A snippet to be validated.</param>
        /// <returns>Enumerable collection of validation results.</returns>
        public override IEnumerable<SnippetValidationResult> Validate(Snippet snippet)
        {
            if (snippet == null)
                throw new ArgumentNullException(nameof(snippet));

            foreach (IGrouping<string, string> grp in snippet.Namespaces.GroupBy(f => f, _stringComparer))
            {
                if (grp.CountExceeds(1))
                {
                    yield return new SnippetValidationResult(
                        snippet,
                        ErrorCode.NamespaceDuplicate,
                        $"Namespace '{grp.Key}' is duplicated.",
                        ResultImportance.Warning);
                }
            }
        }
        public void append()
        {
            var snippet = new Snippet("the sample");
            snippet.Append("something", 5);

            snippet.Text.ShouldEqual("something" + Environment.NewLine);
            snippet.Start.ShouldEqual(5);
            snippet.End.ShouldEqual(5);

            snippet.Append("else", 6);
            snippet.Append("and more", 7);

            snippet.Start.ShouldEqual(5);
            snippet.End.ShouldEqual(7);

            snippet.Text.ShouldEqual(@"something{0}else{0}and more{0}".ToFormat(Environment.NewLine).TrimStart());
            
        }
        /// <summary>
        /// Validates assembly references of the specified <see cref="Snippet"/>.
        /// </summary>
        /// <param name="snippet">A snippet to be validated.</param>
        /// <returns>Enumerable collection of validation results.</returns>
        public override IEnumerable<SnippetValidationResult> Validate(Snippet snippet)
        {
            if (snippet == null)
                throw new ArgumentNullException(nameof(snippet));

            foreach (AssemblyReference reference in snippet.AssemblyReferences)
            {
                if (string.IsNullOrEmpty(reference.AssemblyName))
                {
                    yield return new SnippetValidationResult(
                        snippet,
                        ErrorCode.MissingAssemblyReferenceName,
                        "Snippet assembly reference name is missing.",
                        ResultImportance.Error,
                        reference);
                }
            }
        }
Example #16
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (currentSnippet != null)
            {
                if (action != "insert")
                {
                    Language language = new Language();
                    language.Id = (int)cmbLanguage.SelectedValue;
                    language.Name = cmbLanguage.Name;
                    currentSnippet.Language = language;
                }
                else
                {
                    currentSnippet = new Snippet();
                    currentSnippet.Text = rtxtCode.Text;
                    currentSnippet.Title = txtNotes.Text;
                    currentSnippet.AccessLevel = new AccessLevel();
                    currentSnippet.AccessLevel.Id = (int)cmbAccessLevel.SelectedValue;
                    currentSnippet.AccessLevel.Name = cmbAccessLevel.SelectedText;
                    currentSnippet.Description = txtDescription.Text;
                    currentSnippet.Language = new Language();
                    currentSnippet.Language.Id = (int)cmbLanguage.SelectedValue;
                    currentSnippet.Language.DisplayName = cmbAccessLevel.SelectedText;
                    currentSnippet.Notes = txtNotes.Text;
                    currentSnippet.Usage = txtUsage.Text;
                    currentSnippet.UserId = user.Id;

                    currentSnippet = this.BuildSnippet();
                }

                if (codeKeep != null)
                    if (action == "insert")
                        codeKeep.AddSnippet(currentSnippet);
                    else
                        codeKeep.UpdateSnippet(currentSnippet);
            }

            btnSave.Enabled = false;
        }
        public void ReadXml(XmlReader reader)
        {
            var elementName = string.Empty;
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element)
                {
                    elementName = reader.Name;
                    if (elementName == "Snippets")
                    {
                        var subReader = reader.ReadSubtree();
                        var snippets = new List<Snippet>();
                        while (subReader.ReadToFollowing("Snippet"))
                        {
                            var snippet = new Snippet();
                            snippet.ReadXml(subReader);
                            snippets.Add(snippet);
                        }
                        Snippets = snippets.ToArray();
                        break;
                    }

                }
                else if (reader.NodeType == XmlNodeType.Text)
                {
                    switch (elementName)
                    {
                        case "Keywords":
                            Keywords = reader.Value.Split(' ');
                            break;
                    }
                }
                else if (reader.NodeType == XmlNodeType.EndElement)
                {
                    elementName = string.Empty;
                }
            }
        }
        /// <summary>
        /// Validates a format version of the specified <see cref="Snippet"/>.
        /// </summary>
        /// <param name="snippet">A snippet to be validated.</param>
        /// <returns>Enumerable collection of validation results.</returns>
        public override IEnumerable<SnippetValidationResult> Validate(Snippet snippet)
        {
            if (snippet == null)
                throw new ArgumentNullException(nameof(snippet));

            if (snippet.FormatVersion == null)
            {
                yield return new SnippetValidationResult(
                    snippet,
                    ErrorCode.MissingVersion,
                    "Snippet format version is missing.",
                    ResultImportance.Error);
            }

            if (!ValidationHelper.IsValidVersion(snippet.FormatVersion))
            {
                yield return new SnippetValidationResult(
                    snippet,
                    ErrorCode.InvalidVersion,
                    "Snippet format version is has invalid format.",
                    ResultImportance.Error);
            }
        }
        /// <summary>
        /// Validates a title of the specified <see cref="Snippet"/>.
        /// </summary>
        /// <param name="snippet">A snippet to be validated.</param>
        /// <returns>Enumerable collection of validation results.</returns>
        public override IEnumerable<SnippetValidationResult> Validate(Snippet snippet)
        {
            if (snippet == null)
                throw new ArgumentNullException(nameof(snippet));

            if (snippet.Title.Length == 0)
            {
                yield return new SnippetValidationResult(
                    snippet,
                    ErrorCode.MissingTitle,
                    "Snippet title is missing.",
                    ResultImportance.Error);
            }

            if (string.IsNullOrWhiteSpace(snippet.Title))
            {
                yield return new SnippetValidationResult(
                    snippet,
                    ErrorCode.TitleTitleContainsWhiteSpaceOnly,
                    "Snippet title contains white-space only.",
                    ResultImportance.Error);
            }
        }
        /// <summary>
        /// Validates a shortcut of the specified <see cref="Snippet"/>.
        /// </summary>
        /// <param name="snippet">A snippet to be validated.</param>
        /// <returns>Enumerable collection of validation results.</returns>
        public override IEnumerable<SnippetValidationResult> Validate(Snippet snippet)
        {
            if (snippet == null)
                throw new ArgumentNullException(nameof(snippet));

            if (string.IsNullOrEmpty(snippet.Shortcut))
            {
                yield return new SnippetValidationResult(
                    snippet,
                    ErrorCode.MissingShortcut,
                    "Snippet shortcut is missing.",
                    ResultImportance.Error);
            }

            if (!ValidationHelper.IsValidShortcut(snippet.Shortcut))
            {
                yield return new SnippetValidationResult(
                    snippet,
                    ErrorCode.InvalidShortcut,
                    "Snippet shortcut is invalid.",
                    ResultImportance.Error);
            }
        }
Example #21
0
 private static bool SnippetAreConnected(Snippet first, Snippet second)
 {
     if (first.End == null || second.Begin == null)
         return false;
     if (first.End.SourceContext != second.Begin.SourceContext)
         return false;
     if (first.End.Offset != second.Begin.Offset)
         return false;
     return true;
 }
Example #22
0
        public SourceWriter WriteCode(IEnumerable<Snippet> snippets)
        {
            // compact snippets so vs language service doesn't have to
            var compacted = new Snippets(snippets.Count());
            Snippet prior = null;
            foreach (var snippet in snippets)
            {
                if (prior != null && SnippetAreConnected(prior, snippet))
                {
                    prior = new Snippet
                    {
                        Value = prior.Value + snippet.Value,
                        Begin = prior.Begin,
                        End = snippet.End
                    };
                    continue;
                }

                if (prior != null)
                    compacted.Add(prior);
                prior = snippet;
            }

            if (prior != null)
                compacted.Add(prior);

            // write them out and keep mapping-to-spark source information
            foreach (var snippet in compacted)
            {
                if (snippet.Begin != null)
                {
                    Mappings.Add(new SourceMapping
                    {
                        Source = snippet,
                        OutputBegin = Length,
                        OutputEnd = Length + snippet.Value.Length
                    });
                }

                Write(snippet.Value);
            }

            return this;
        }
Example #23
0
        internal void InsertSnippet(Snippet snip, int startPos)
        {
            NativeScintilla.BeginUndoAction();
            IsActive = false;

            string snippet = snip.RealCode;

            //	First properly indent the template. We do this by
            //	getting the indent string of the current line and
            //	adding it to all newlines
            int indentPoint = 0;
            string line = Scintilla.Lines.Current.Text;
            if(line != string.Empty)
            {				
                while (indentPoint < line.Length)
                {
                    char c = line[indentPoint];
                    if (c != ' ' && c != '\t')
                        break;

                    indentPoint++;
                }
            }

            //	Grab the current selected text in case we have a surrounds with scenario.
            string selText = Scintilla.Selection.Text;
            //	Now we clear the selection
            if (selText != string.Empty)
                Scintilla.Selection.Clear();

            if (indentPoint > 0)
            {
                string indent = line.Substring(0, indentPoint);

                //	This is a bit of a tough decision, but I think the best way to handle it
                //	is to assume that the Snippet's Eol Marker matches the Platform DOCUMENT_DEFAULT
                //	but the target Eol Marker should match the Document's.
                snippet = snippet.Replace(Environment.NewLine, Scintilla.EndOfLine.EolString + indent);

                //	Same deal with the selected text if any				
                selText = selText.Replace(Environment.NewLine, Scintilla.EndOfLine.EolString + indent);
            }

            int anchorPos = -1;
            int caretPos = -1;
            int endPos = -1;
            int selPos = -1;
            SortedList<int, int> dropMarkers = new SortedList<int, int>();
            SortedList<int, SnippetLinkRange> indexedRangesToActivate = new SortedList<int, SnippetLinkRange>();
            List<SnippetLinkRange> unindexedRangesToActivate = new List<SnippetLinkRange>();
            Match m = snippetRegex1.Match(snippet);

            while (m.Success)
            {
                //	Did it match a $DropMarker$ token?
                if (m.Groups["dm"].Success)
                {
                    //	Yep, was it an indexed or unindexed DropMarker
                    if (m.Groups["dmi"].Success)
                    {
                        //	Indexed, set the indexed drop marker's character offset
                        //	if it is specified more than once the last one wins.
                        dropMarkers[int.Parse(m.Groups["dmi"].Value)] = m.Groups["dm"].Index;
                    }
                    else
                    {
                        //	Unindexed, just tack it on at the _end
                        dropMarkers[dropMarkers.Count] = m.Groups["dm"].Index;
                    }

                    //	Take the token out of the string
                    snippet = snippet.Remove(m.Groups["dm"].Index, m.Groups["dm"].Length);
                }
                else if (m.Groups["c"].Success)
                {
                    //	We matched the $Caret$ Token. Since there can be 
                    //	only 1 we set the caretPos. If this is specified
                    //	more than once the last one wins
                    caretPos = m.Groups["c"].Index;

                    //	Take the token out of the string
                    snippet = snippet.Remove(m.Groups["c"].Index, m.Groups["c"].Length);
                }
                else if (m.Groups["a"].Success)
                {
                    //	We matched the $Anchor$ Token. Since there can be 
                    //	only 1 we set the anchorPos. If this is specified
                    //	more than once the last one wins
                    anchorPos = m.Groups["a"].Index;

                    //	Take the token out of the string
                    snippet = snippet.Remove(m.Groups["a"].Index, m.Groups["a"].Length);
                }
                else if (m.Groups["e"].Success)
                {
                    //	We matched the $End$ Token. Since there can be 
                    //	only 1 we set the endPos. If this is specified
                    //	more than once the last one wins
                    endPos = m.Groups["e"].Index;

                    //	Take the token out of the string
                    snippet = snippet.Remove(m.Groups["e"].Index, m.Groups["e"].Length);
                }
                else if (m.Groups["s"].Success)
                {
                    //	We matched the $Selection$ Token. Simply insert the
                    //	selected text at this position
                    selPos = m.Groups["s"].Index;

                    //	Take the token out of the string
                    snippet = snippet.Remove(m.Groups["s"].Index, m.Groups["s"].Length);
                    snippet = snippet.Insert(m.Groups["s"].Index, selText);
                }
                else if (m.Groups["l"].Success)
                {
                    //	Finally match for Snippet Link Ranges. This is at the bottom of the if/else
                    //	because we want the more specific regex groups to match first so that this
                    //	generic expression group doesn't create a SnippetLinkRange for say the 
                    //	$Caret$ Token.
                    Group g = m.Groups["l"];

                    int rangeIndex;
                    string groupKey;

                    if (m.Groups["li"].Success)
                    {
                        //	We have a subindexed SnippetLinkRange along the lines of $sometoken[1]$
                        Group sg = m.Groups["li"];

                        //	At this point g.Value = $sometoken[1]$
                        //	and sg.Value = [1].
                        //	We want the range's Key, which would be sometoken
                        groupKey = g.Value.Substring(1, g.Value.Length - sg.Length - 2);

                        //	Now we need the range's Index which would be 1 in our fictitional case
                        rangeIndex = int.Parse(sg.Value.Substring(1, sg.Value.Length - 2));

                        //	Now we need to determine the actual _start and _end positions of the range.
                        //	Keep in mind we'll be stripping out the 2 $ and the subindex string (eg [1])
                        int start = startPos + g.Index;
                        int end = start + g.Length - sg.Length - 2;

                        //	And now we add (or replace) the snippet link range at the index
                        //	keep in mind duplicates will stomp all over each other, the last
                        //	one wins. Replaced tokens won't get a range
                        indexedRangesToActivate[rangeIndex] = new SnippetLinkRange(start, end, Scintilla, groupKey); ;

                        //	And remove all the token info including the subindex from the snippet text 
                        //	leaving only the key
                        snippet = snippet.Remove(g.Index, 1).Remove(g.Index - 2 + g.Length - sg.Length, sg.Length + 1);
                    }
                    else
                    {
                        //	We have a regular old SnippetLinkRange along the lines of $sometoken$

                        //	We want the range's Key, which would be sometoken
                        groupKey = g.Value.Substring(1, g.Value.Length - 2);

                        //	Now we need to determine the actual _start and _end positions of the range.
                        //	Keep in mind we'll be stripping out the 2 $
                        int start = startPos + g.Index;
                        int end = start + g.Length - 2;

                        //	Now create the range object
                        unindexedRangesToActivate.Add(new SnippetLinkRange(start, end, Scintilla, groupKey));

                        //	And remove all the token info from the snippet text 
                        //	leaving only the key
                        snippet = snippet.Remove(g.Index, 1).Remove(g.Index + g.Length - 2, 1);
                    }
                }
                //	Any more matches? Note that I'm rerunning the regexp query
                //	on the snippet string becuase it's contents have been modified
                //	and we need to get the updated index values.
                m = snippetRegex1.Match(snippet);
            }

            //	Replace the snippet Keyword with the snippet text. Or if this
            //	isn't triggered by a shortcut, it will insert at the current
            //	Caret Position
            Scintilla.GetRange(startPos, NativeScintilla.GetCurrentPos()).Text = snippet;

            //	Now that we have the text set we can activate our link ranges
            //	we couldn't do it before becuase they were managed ranges and
            //	would get offset by the text change

            //	Since we are done adding new SnippetLinkRanges we can tack
            //	on the unindexed ranges to the _end of the indexed ranges
            SnippetLinkRange[] allLinks = new SnippetLinkRange[indexedRangesToActivate.Count + unindexedRangesToActivate.Count];
            for (int i = 0; i < indexedRangesToActivate.Values.Count; i++)
                allLinks[i] = indexedRangesToActivate[i];

            for (int i = 0; i < unindexedRangesToActivate.Count; i++)
                allLinks[i + indexedRangesToActivate.Count] = unindexedRangesToActivate[i];

            foreach (SnippetLinkRange slr in allLinks)
                addSnippetLink(slr);

            foreach (SnippetLinkRange slr in allLinks)
                slr.Init();

            //	Now we need to activate the Snippet links. However we have a bit
            //	of a styling confilct. If we set the indicator styles before the
            //	SQL Lexer styles the newly added text it won't get styled. So to
            //	make sure we set the Indicator Styles after we put the call on
            //	a timer.
            if (_snippetLinks.Count > 0)
            {
                Timer t = new Timer();
                t.Interval = 10;

                //	Oh how I love anonymous delegates, this is starting to remind
                //	me of JavaScript and SetTimeout...
                t.Tick += new EventHandler(delegate(object sender, EventArgs te)
                {
                    t.Dispose();
                    IsActive = true;
                });
                t.Start();
            }

            //	Add all the Drop markers in the indexed order. The
            //	order is reversed of course because drop markers work
            //	in a FILO manner
            for (int i = dropMarkers.Count - 1; i >= 0; i--)
                Scintilla.DropMarkers.Drop(startPos + dropMarkers.Values[i]);

            //	Place the caret at either the position of the token or
            //	at the _end of the snippet text.
            if (caretPos >= 0)
                Scintilla.Caret.Goto(startPos + caretPos);
            else
                Scintilla.Caret.Goto(startPos + snippet.Length);

            //	Ahoy, way anchor!
            if (anchorPos >= 0)
                Scintilla.Caret.Anchor = startPos + anchorPos;

            //	Do we have an _end cursor?
            if (endPos >= 0)
            {
                //	If they have snippet link ranges activated in this snippet
                //	go ahead and set up an EndPoint marker
                if (allLinks.Length > 0)
                {
                    SnippetLinkEnd eci = new SnippetLinkEnd(endPos + startPos, Scintilla);
                    Scintilla.ManagedRanges.Add(eci);
                    _snippetLinks.EndPoint = eci;
                }
                else
                {
                    //	Otherwise we treat it like an Anchor command because
                    //	the SnippetLink mode isn't activated
                    Scintilla.Caret.Goto(endPos + startPos);
                }
            }

            NativeScintilla.EndUndoAction();
        }
Example #24
0
 public void InsertSnippet(Snippet snip)
 {
     InsertSnippet(snip, Math.Min(NativeScintilla.GetCurrentPos(), NativeScintilla.GetAnchor()));
 }
 public void TabIndentation() {
     var snippet = new Snippet(
         "forprops",
         "for (var property in object) {\r\n\tif (object.hasOwnProperty(property)) {\r\n\t\t$body$\r\n\t}\r\n};",
         new Declaration("p", "for (var p in object) {\r\n\tif (object.hasOwnProperty(p)) {\r\n\t\t$body$\r\n\t}\r\n};")
     );
     using (var solution = BasicProject.Generate().ToVs()) {
         using (new SnippetTestOptionHolder(insertTabs: true, indentSize: 8, tabSize: 8)) {
             TestOneInsertSnippet(solution, snippet, "Nodejs");
             solution.CloseActiveWindow(vsSaveChanges.vsSaveChangesNo);
         }
     }
 }
 public void IndentSize() {
     var snippet = new Snippet(
         "tryf",
         "try {\r\n  $body$\r\n} catch (e) {\r\n  \r\n} finally {\r\n  \r\n};",
         new Declaration("exception", "try {\r\n  $body$\r\n} catch (exception) {\r\n  \r\n} finally {\r\n  \r\n};")
     );
     using (var solution = BasicProject.Generate().ToVs()) {
         using (new SnippetTestOptionHolder(insertTabs: false, indentSize: 2, tabSize: 2)) {
             TestOneInsertSnippet(solution, snippet, "Nodejs");
             solution.CloseActiveWindow(vsSaveChanges.vsSaveChangesNo);
         }
     }
 }
        private static IEditor VerifySnippet(Snippet snippet, string body, IEditor server, bool insertViaMenu = false) {
            if (insertViaMenu) {
                Keyboard.Type(snippet.Shortcut + "\t"); // one tab for auto completion, one tab for snippet
            }
            else {
                Keyboard.Type(snippet.Shortcut + "\t\t");
            }

            server.WaitForText(snippet.Expected.Replace("$body$", body));

            foreach (var decl in snippet.Declarations) {
                Console.WriteLine("Declaration: {0}", decl.Replacement);
                Keyboard.Type(decl.Replacement);
                Keyboard.Type("→");
                server.WaitForText(decl.Expected.Replace("$body$", body));
                Keyboard.Type("\t");
            }
            Keyboard.Type("\r");
            return server;
        }
        private static IEditor TestOneTabSnippet(IVisualStudioInstance solution, Snippet snippet) {
            Console.WriteLine("Testing: {0}", snippet.Shortcut);
            var server = solution.OpenItem("SnippetsTest", "server.js");
            server.MoveCaret(1, 1);
            server.Invoke(() => server.TextView.Caret.EnsureVisible());
            server.SetFocus();

            return VerifySnippet(snippet, "", server);
        }
        public void Selected() {
            var snippet = new Snippet(
                "if",
                "if (true) {\r\n    $body$\r\n}",
                new Declaration("false", "if (false) {\r\n    $body$\r\n}")
            );
            using (var solution = BasicProject.Generate().ToVs()) {
                using (new SnippetTestOptionHolder()) {
                    var app = TestOneTabSnippet(solution, snippet);

                    Keyboard.Type("testing");
                    app.WaitForText("if (false) {\r\n    testing\r\n}");

                    solution.CloseActiveWindow(vsSaveChanges.vsSaveChangesNo);
                }
            }
        }
        private static IEditor TestOneSurroundWithSnippet(IVisualStudioInstance solution, Snippet snippet, string category, string body = "nonempty", string file = "nonempty.js") {
            Console.WriteLine("Testing: {0}", snippet.Shortcut);
            var server = solution.OpenItem("SnippetsTest", file);
            server.Select(1, 1, server.Text.Length);
            server.Invoke(() => server.TextView.Caret.EnsureVisible());
            server.SetFocus();

            solution.ExecuteCommand("Edit.SurroundWith");
            Keyboard.Type(category + "\t");

            return VerifySnippet(snippet, body, server, insertViaMenu: true);
        }