/// <summary> /// Processes the snippet and template arguments /// </summary> public static Int32 PostProcessSnippets(ScintillaControl sci, Int32 currentPosition) { Int32 delta = 0; while (sci.SelectText(BOUNDARY, 0) != -1) { sci.ReplaceSel(""); delta -= BOUNDARY.Length; } String text = sci.Text; // Store text temporarily Int32 entryPosition = sci.MBSafePosition(text.IndexOfOrdinal(ENTRYPOINT)); Int32 exitPosition = sci.MBSafePosition(text.IndexOfOrdinal(EXITPOINT)); if (entryPosition != -1 && exitPosition != -1) { sci.SelectText(ENTRYPOINT, 0); sci.ReplaceSel(""); delta -= ENTRYPOINT.Length; sci.SelectText(EXITPOINT, 0); sci.ReplaceSel(""); delta -= EXITPOINT.Length; sci.SetSel(entryPosition, exitPosition - ENTRYPOINT.Length); } else if (entryPosition != -1 && exitPosition == -1) { sci.SelectText(ENTRYPOINT, 0); sci.ReplaceSel(""); delta -= ENTRYPOINT.Length; sci.SetSel(entryPosition, entryPosition); } else sci.SetSel(currentPosition, currentPosition); return delta; }
private static void ConvertToConst(ClassModel inClass, ScintillaControl sci, MemberModel member, bool detach) { String suggestion = "NEW_CONST"; String label = TextHelper.GetString("ASCompletion.Label.ConstName"); String title = TextHelper.GetString("ASCompletion.Title.ConvertToConst"); Hashtable info = new Hashtable(); info["suggestion"] = suggestion; info["label"] = label; info["title"] = title; DataEvent de = new DataEvent(EventType.Command, "ProjectManager.LineEntryDialog", info); EventManager.DispatchEvent(null, de); if (!de.Handled) return; suggestion = (string)info["suggestion"]; int position = sci.CurrentPos; int style = sci.BaseStyleAt(position); MemberModel latest = null; int wordPosEnd = position + 1; int wordPosStart = position; while (sci.BaseStyleAt(wordPosEnd) == style) wordPosEnd++; while (sci.BaseStyleAt(wordPosStart - 1) == style) wordPosStart--; sci.SetSel(wordPosStart, wordPosEnd); string word = sci.SelText; sci.ReplaceSel(suggestion); if (member == null) { detach = false; lookupPosition = -1; position = sci.WordStartPosition(sci.CurrentPos, true); sci.SetSel(position, sci.WordEndPosition(position, true)); } else { latest = GetLatestMemberForVariable(GeneratorJobType.Constant, inClass, Visibility.Private, new MemberModel("", "", FlagType.Static, 0)); if (latest != null) { position = FindNewVarPosition(sci, inClass, latest); } else { position = GetBodyStart(inClass.LineFrom, inClass.LineTo, sci); detach = false; } if (position <= 0) return; sci.SetSel(position, position); } MemberModel m = NewMember(suggestion, member, FlagType.Variable | FlagType.Constant | FlagType.Static, GetDefaultVisibility(inClass)); var features = ASContext.Context.Features; switch (style) { case 4: m.Type = features.numberKey; break; case 6: case 7: m.Type = features.stringKey; break; } m.Value = word; GenerateVariable(m, position, detach); }
/// <summary> /// /// </summary> public static bool ReplaceText(ScintillaControl sci, String tail, char trigger) { sci.BeginUndoAction(); try { String triggers = PluginBase.Settings.InsertionTriggers ?? ""; if (triggers.Length > 0 && Regex.Unescape(triggers).IndexOf(trigger) < 0) return false; ICompletionListItem item = null; if (completionList.SelectedIndex >= 0) { item = completionList.Items[completionList.SelectedIndex] as ICompletionListItem; } Hide(); if (item != null) { String replace = item.Value; if (replace != null) { sci.SetSel(startPos, sci.CurrentPos); if (word != null && tail.Length > 0) { if (replace.StartsWith(word, StringComparison.OrdinalIgnoreCase) && replace.IndexOfOrdinal(tail) >= word.Length) { replace = replace.Substring(0, replace.IndexOfOrdinal(tail)); } } sci.ReplaceSel(replace); if (OnInsert != null) OnInsert(sci, startPos, replace, trigger, item); if (tail.Length > 0) sci.ReplaceSel(tail); } return true; } return false; } finally { sci.EndUndoAction(); } }
/// <summary> /// Handles the incoming character /// </summary> public static void OnChar(ScintillaControl sci, Int32 value) { if (cType == XMLType.Invalid || (sci.ConfigurationLanguage != "xml" && sci.ConfigurationLanguage != "html")) return; XMLContextTag ctag; Int32 position = sci.CurrentPos; if (sci.BaseStyleAt(position) == 6 && value != '"') return; // in XML attribute Char c = ' '; DataEvent de; switch (value) { case 10: // Shift+Enter to insert <BR/> Int32 line = sci.LineFromPosition(position); if (Control.ModifierKeys == Keys.Shift) { ctag = GetXMLContextTag(sci, position); if (ctag.Tag == null || ctag.Tag.EndsWith(">")) { int start = sci.PositionFromLine(line)-((sci.EOLMode == 0)? 2:1); sci.SetSel(start, position); sci.ReplaceSel((PluginSettings.UpperCaseHtmlTags) ? "<BR/>" : "<br/>"); sci.SetSel(start+5, start+5); return; } } if (PluginSettings.SmartIndenter) { // There is no standard for XML formatting, although most IDEs have similarities. We are mostly going with Visual Studio style with slight differences. // Get last non-empty line. String text = ""; Int32 line2 = line - 1; while (line2 >= 0 && text.Length == 0) { text = sci.GetLine(line2).TrimEnd(); line2--; } if ((text.EndsWith(">") && !text.EndsWith("?>") && !text.EndsWith("%>")) || text.EndsWith("<!--") || text.EndsWith("<![CDATA[")) { // Get the previous tag. do { position--; c = (Char)sci.CharAt(position); } while (position > 0 && c != '>'); ctag = GetXMLContextTag(sci, c == '>' ? position + 1 : position); // Line indentation. Int32 indent = sci.GetLineIndentation(line2 + 1); String checkStart = null; bool subIndent = true; if (text.EndsWith("<!--")) { checkStart = "-->"; subIndent = false; } else if (text.EndsWith("<![CDATA[")) { checkStart = "]]>"; subIndent = false; } else if (ctag.Closed || ctag.Closing) { //Closed tag. Look for the nearest open and not closed tag for proper indentation subIndent = false; if (ctag.Name != null) { var tmpTags = new Stack<XMLContextTag>(); var tmpTag = ctag; if (!tmpTag.Closed) tmpTags.Push(tmpTag); while (tmpTag.Position != 0) { tmpTag = GetXMLContextTag(sci, tmpTag.Position); if (tmpTag.Tag != null && tmpTag.Name != null) { if (tmpTag.Closed) continue; else if (tmpTag.Closing) { tmpTags.Push(tmpTag); } else { if (tmpTags.Count > 0 && tmpTags.Peek().Name == tmpTag.Name) tmpTags.Pop(); else break; } } } if (tmpTags.Count > 0) indent = sci.GetLineIndentation(sci.LineFromPosition(tmpTags.Pop().Position)); else if (tmpTag.Name != null) { subIndent = true; checkStart = "</" + tmpTag.Name; indent = sci.GetLineIndentation(sci.LineFromPosition(tmpTag.Position)); } else { indent = sci.GetLineIndentation(sci.LineFromPosition(tmpTag.Position)); } } } else if (ctag.Name != null) { // Indentation. Some IDEs use the tag position, VS uses the tag start line indentation. indent = sci.GetLineIndentation(sci.LineFromPosition(ctag.Position)); checkStart = "</" + ctag.Name; if (ctag.Name.ToLower() == "script" || ctag.Name.ToLower() == "style") subIndent = false; } try { sci.BeginUndoAction(); if (checkStart != null) { text = sci.GetLine(line).TrimStart(); if (text.StartsWith(checkStart)) { sci.SetLineIndentation(line, indent); sci.InsertText(sci.PositionFromLine(line), LineEndDetector.GetNewLineMarker(sci.EOLMode)); } } // Indent the code if (subIndent) indent += sci.Indent; sci.SetLineIndentation(line, indent); position = sci.LineIndentPosition(line); sci.SetSel(position, position); } finally { sci.EndUndoAction(); } return; } else if (!text.EndsWith(">")) { ctag = GetXMLContextTag(sci, sci.CurrentPos); if (ctag.Tag == null || ctag.Name == null) return; // We're inside a tag. Visual Studio indents with regards to the first line, other IDEs indent using the indentation of the last line with text. int indent; string tag = (ctag.Tag.IndexOf('\r') > 0 || ctag.Tag.IndexOf('\n') > 0) ? ctag.Tag.Substring(0, ctag.Tag.IndexOfAny(new[] {'\r', '\n'})).TrimEnd() : ctag.Tag.TrimEnd(); if (tag.EndsWith("\"")) { int i; int l = tag.Length; for (i = ctag.Name.Length + 1; i < l; i++) { if (!char.IsWhiteSpace(tag[i])) break; } indent = sci.Column(ctag.Position) + sci.MBSafePosition(i); } else { indent = sci.GetLineIndentation(sci.LineFromPosition(ctag.Position)) + sci.Indent; } sci.SetLineIndentation(line, indent); position = sci.LineIndentPosition(line); sci.SetSel(position, position); return; } } break; case '<': case '/': if (value == '/') { if ((position < 2) || ((Char)sci.CharAt(position-2) != '<')) return; ctag = new XMLContextTag(); ctag.Position = position - 2; ctag.Closing = true; } else { ctag = GetXMLContextTag(sci, position); if (ctag.Tag != null) return; } // Allow another plugin to handle this de = new DataEvent(EventType.Command, "XMLCompletion.Element", ctag); EventManager.DispatchEvent(PluginBase.MainForm, de); if (de.Handled) return; // New tag if (PluginSettings.EnableXMLCompletion && cType == XMLType.Known) { List<ICompletionListItem> items = new List<ICompletionListItem>(); String previous = null; foreach (string ns in namespaces) { items.Add(new NamespaceItem(ns)); } foreach (HTMLTag tag in knownTags) if (tag.Name != previous && (tag.NS == "" || tag.NS == defaultNS)) { items.Add( new HtmlTagItem(tag.Name, tag.Tag)); previous = tag.Name; } items.Sort(new ListItemComparer()); CompletionList.Show(items, true); } return; case ':': ctag = GetXMLContextTag(sci, position); if (ctag.NameSpace == null || position - ctag.Position > ctag.Name.Length + 2) return; // Allow another plugin to handle this de = new DataEvent(EventType.Command, "XMLCompletion.Namespace", ctag); EventManager.DispatchEvent(PluginBase.MainForm, de); if (de.Handled) return; // Show namespace's tags if (PluginSettings.EnableXMLCompletion && cType == XMLType.Known) { List<ICompletionListItem> items = new List<ICompletionListItem>(); String previous = null; foreach (HTMLTag tag in knownTags) if (tag.Name != previous && tag.NS == ctag.NameSpace) { items.Add(new HtmlTagItem(tag.Name, tag.Name)); previous = tag.Name; } CompletionList.Show(items, true); } return; case '>': if (PluginSettings.CloseTags) { ctag = GetXMLContextTag(sci, position); if (ctag.Name != null && !ctag.Closed) { // Allow another plugin to handle this de = new DataEvent(EventType.Command, "XMLCompletion.CloseElement", ctag); EventManager.DispatchEvent(PluginBase.MainForm, de); if (de.Handled) return; if (ctag.Closing) return; Boolean isLeaf = false; if (cType == XMLType.Known) foreach(HTMLTag tag in knownTags) { if (String.Compare(tag.Tag, ctag.Name, true) == 0) { isLeaf = tag.IsLeaf; break; } } if (isLeaf) { sci.SetSel(position-1,position); sci.ReplaceSel("/>"); sci.SetSel(position+1, position+1); } else { String closeTag = "</"+ctag.Name+">"; sci.ReplaceSel(closeTag); sci.SetSel(position, position); } } } return; case ' ': c = (char)sci.CharAt(position); if (c > 32 && c != '/' && c != '>' && c != '<') return; ctag = GetXMLContextTag(sci, position); if (ctag.Tag != null) { if (InQuotes(ctag.Tag) || ctag.Tag.LastIndexOf('"') < ctag.Tag.LastIndexOf('=')) return; // Allow another plugin to handle this Object[] obj = new Object[] { ctag, "" }; de = new DataEvent(EventType.Command, "XMLCompletion.Attribute", obj); EventManager.DispatchEvent(PluginBase.MainForm, de); if (de.Handled) return; if (PluginSettings.EnableXMLCompletion && cType == XMLType.Known) { foreach (HTMLTag tag in knownTags) if (String.Compare(tag.Tag, ctag.Name, true) == 0) { List<ICompletionListItem> items = new List<ICompletionListItem>(); String previous = null; foreach (String attr in tag.Attributes) if (attr != previous) { items.Add(new HtmlAttributeItem(attr)); previous = attr; } CompletionList.Show(items, true); return; } } } /*else { if (Control.ModifierKeys == Keys.Shift) { sci.SetSel(position - 1, position); sci.ReplaceSel(" "); } }*/ return; case '=': if (PluginSettings.InsertQuotes) { ctag = GetXMLContextTag(sci, position); position = sci.CurrentPos-2; if (ctag.Tag != null && !String.IsNullOrEmpty(ctag.Name) && Char.IsLetter(ctag.Name[0]) && !InQuotes(ctag.Tag) && (GetWordLeft(sci, ref position).Length > 0)) { position = sci.CurrentPos; c = (Char)sci.CharAt(position); if (c > 32 && c != '>') sci.ReplaceSel("\"\" "); else sci.ReplaceSel("\"\""); sci.SetSel(position+1, position+1); justInsertedQuotesAt = position+1; // Allow another plugin to handle this de = new DataEvent(EventType.Command, "XMLCompletion.AttributeValue", new Object[] { ctag, string.Empty }); EventManager.DispatchEvent(PluginBase.MainForm, de); } } return; case '"': ctag = GetXMLContextTag(sci, position); if (position > 1 && ctag.Tag != null && !ctag.Tag.StartsWith("<!")) { // TODO Colorize text change to highlight what's been done if (justInsertedQuotesAt == position - 1) { justInsertedQuotesAt = -1; c = (Char)sci.CharAt(position - 2); if (c == '"' && (Char)sci.CharAt(position-2) == '"') { sci.SetSel(position - 2, position); sci.ReplaceSel("\""); } // Allow another plugin to handle this de = new DataEvent(EventType.Command, "XMLCompletion.AttributeValue", new Object[] {ctag, string.Empty}); EventManager.DispatchEvent(PluginBase.MainForm, de); } else { c = (Char)sci.CharAt(position - 1); if (c == '"' && (Char)sci.CharAt(position) == '"') { sci.SetSel(position - 1, position + 1); sci.ReplaceSel("\""); } } } break; case '?': case '%': if (PluginSettings.CloseTags && position > 1) { ctag = GetXMLContextTag(sci, position-2); if (ctag.Tag == null || ctag.Tag.EndsWith(">")) { if ((Char)sci.CharAt(position-2) == '<') { sci.ReplaceSel((Char)value + ">"); sci.SetSel(position, position); } } } break; case '!': if (PluginSettings.CloseTags && position > 1) { ctag = GetXMLContextTag(sci, position-2); if (ctag.Tag == null || ctag.Tag.EndsWith(">")) { if ((Char)sci.CharAt(position-2) == '<') { CompletionList.Show(xmlBlocks, true); } } } break; } }
private static void SciInsertAndSelect(ScintillaControl sci, string text) { if (text.Length == 0) return; if (sci.SelText.Length == 0) { sci.InsertText(sci.CurrentPos, text); sci.CurrentPos += text.Length; } else sci.ReplaceSel(text); sci.SetSel(sci.CurrentPos - text.Length , sci.CurrentPos); }
private bool ProcessAbbrevation(ScintillaControl sci) { //if (_settings.abbrevationDictList == null) //{ // System.Windows.Forms.MessageBox.Show("Insert abbreviations before!!"); // return false; //} int start =0; int end = 0; string left = GetWordFromPosition(sci, ref start, ref end); if (left != null) { String ext = System.IO.Path.GetExtension(ASContext.Context.CurrentFile).ToLower(); ; dictAbbreviations = null; if (!settings.abbrevationDictList.TryGetValue(ext, out dictAbbreviations)) { dictAbbreviations = settings.abbrevationDictList[".other"]; } AbbrevationSnippet abbrevationSnippet; if (dictAbbreviations.TryGetValue(left , out abbrevationSnippet)) { sci.GotoPos(start); sci.BeginUndoAction(); CreateWords cwNew; // c'è una abbreviazione lo creo if (currentCreateWords != null) cw_MonitorOnWordsDeactive(currentCreateWords); cwNew = CreateNewWords(); string elaborateText = cwNew.MakeTextFromSnippet(sci, abbrevationSnippet); sci.SetSel(start, end); sci.ReplaceSel(elaborateText); if (abbrevationSnippet.Arguments == null) { cwNew.MonitorOnWordsActive -= new OnMonitorActiveEventHanlder(cw_MonitorOnWordsActive); cwNew.MonitorOnWordsDeactive -= new OnMonitorActiveEventHanlder(cw_MonitorOnWordsDeactive); sci.EndUndoAction(); return true; } DoBeforeMonitor(); // nessuna activazione quindi nessun monitor if (!currentCreateWords.TryActivateMonitor()) { cwNew.MonitorOnWordsActive -= new OnMonitorActiveEventHanlder(cw_MonitorOnWordsActive); cwNew.MonitorOnWordsDeactive -= new OnMonitorActiveEventHanlder(cw_MonitorOnWordsDeactive); } else { currentCreateWords = cwNew; } sci.EndUndoAction(); return true; } } //non ha trovato nessuna parola if (isCursor) { isCursor = false; ShowListAbbrevations(); return false; } if (MonitorWordsActive && currentSci.Focused) currentCreateWords.MoveNextWord(); else ShowListAbbrevations(); return false; }
private static void GenerateDefaultHandlerName(ScintillaControl sci, int position, int targetPos, string eventName, bool closeBrace) { string target = null; int contextOwnerPos = GetContextOwnerEndPos(sci, sci.WordStartPosition(targetPos, true)); if (contextOwnerPos != -1) { ASResult contextOwnerResult = ASComplete.GetExpressionType(sci, contextOwnerPos); if (contextOwnerResult != null && !contextOwnerResult.IsNull() && contextOwnerResult.Member != null) { if (contextOwnerResult.Member.Name == "contentLoaderInfo" && sci.CharAt(contextOwnerPos) == '.') { // we want to name the event from the loader var and not from the contentLoaderInfo parameter contextOwnerPos = GetContextOwnerEndPos(sci, sci.WordStartPosition(contextOwnerPos - 1, true)); if (contextOwnerPos != -1) { contextOwnerResult = ASComplete.GetExpressionType(sci, contextOwnerPos); if (contextOwnerResult != null && !contextOwnerResult.IsNull() && contextOwnerResult.Member != null) { target = contextOwnerResult.Member.Name; } } } else { target = contextOwnerResult.Member.Name; } } } eventName = Camelize(eventName.Substring(eventName.LastIndexOf('.') + 1)); if (target != null) target = target.TrimStart(new char[] { '_' }); switch (ASContext.CommonSettings.HandlerNamingConvention) { case HandlerNamingConventions.handleTargetEventName: if (target == null) contextToken = "handle" + Capitalize(eventName); else contextToken = "handle" + Capitalize(target) + Capitalize(eventName); break; case HandlerNamingConventions.onTargetEventName: if (target == null) contextToken = "on" + Capitalize(eventName); else contextToken = "on" + Capitalize(target) + Capitalize(eventName); break; case HandlerNamingConventions.target_eventNameHandler: if (target == null) contextToken = eventName + "Handler"; else contextToken = target + "_" + eventName + "Handler"; break; default: //HandlerNamingConventions.target_eventName if (target == null) contextToken = eventName; else contextToken = target + "_" + eventName; break; } char c = (char)sci.CharAt(position - 1); if (c == ',') InsertCode(position, "$(Boundary) " + contextToken + "$(Boundary)", sci); else InsertCode(position, contextToken, sci); position = sci.WordEndPosition(position + 1, true); sci.SetSel(position, position); c = (char)sci.CharAt(position); if (c <= 32) if (closeBrace) sci.ReplaceSel(");"); else sci.ReplaceSel(";"); sci.SetSel(position, position); }
public static bool MakePrivate(ScintillaControl Sci, MemberModel member, ClassModel inClass) { ContextFeatures features = ASContext.Context.Features; string visibility = GetPrivateKeyword(inClass); if (features.publicKey == null || visibility == null) return false; Regex rePublic = new Regex(String.Format(@"\s*({0})\s+", features.publicKey)); string line; Match m; int index, position; for (int i = member.LineFrom; i <= member.LineTo; i++) { line = Sci.GetLine(i); m = rePublic.Match(line); if (m.Success) { index = Sci.MBSafeTextLength(line.Substring(0, m.Groups[1].Index)); position = Sci.PositionFromLine(i) + index; Sci.SetSel(position, position + features.publicKey.Length); Sci.ReplaceSel(visibility); UpdateLookupPosition(position, features.publicKey.Length - visibility.Length); return true; } } return false; }
/// <summary> /// Inserts the specified snippet to the document /// </summary> public static Int32 InsertSnippetText(ScintillaControl sci, Int32 currentPosition, String snippet) { sci.BeginUndoAction(); try { Int32 newIndent; String text = snippet; if (sci.SelTextSize > 0) currentPosition -= sci.MBSafeTextLength(sci.SelText); Int32 line = sci.LineFromPosition(currentPosition); Int32 indent = sci.GetLineIndentation(line); sci.ReplaceSel(""); Int32 lineMarker = LineEndDetector.DetectNewLineMarker(text, sci.EOLMode); String newline = LineEndDetector.GetNewLineMarker(lineMarker); if (newline != "\n") text = text.Replace(newline, "\n"); newline = LineEndDetector.GetNewLineMarker((Int32)PluginBase.MainForm.Settings.EOLMode); text = PluginBase.MainForm.ProcessArgString(text).Replace(newline, "\n"); newline = LineEndDetector.GetNewLineMarker(sci.EOLMode); String[] splitted = text.Trim().Split('\n'); for (Int32 j = 0; j < splitted.Length; j++) { if (j != splitted.Length - 1) sci.InsertText(sci.CurrentPos, splitted[j] + newline); else sci.InsertText(sci.CurrentPos, splitted[j]); sci.CurrentPos += sci.MBSafeTextLength(splitted[j]) + newline.Length; if (j > 0) { line = sci.LineFromPosition(sci.CurrentPos - newline.Length); newIndent = sci.GetLineIndentation(line) + indent; sci.SetLineIndentation(line, newIndent); } } Int32 length = sci.CurrentPos - currentPosition - newline.Length; Int32 delta = PostProcessSnippets(sci, currentPosition); return length + delta; } finally { sci.EndUndoAction(); } }
static public void OnChar(ScintillaControl sci, int value) { if (cType == XMLType.Invalid) return; XMLContextTag ctag; int position = sci.CurrentPos; char c = ' '; switch (value) { case 10: int line = sci.LineFromPosition(position); // Shift+Enter to insert <BR/> if (Control.ModifierKeys == Keys.Shift) { ctag = GetXMLContextTag(sci, position); if (ctag.Tag == null || ctag.Tag.EndsWith(">")) { int start = sci.PositionFromLine(line)-((sci.EOLMode == 0)? 2:1); sci.SetSel(start, position); sci.ReplaceSel((lowerCaseHtmlTags)?"<br/>":"<BR/>"); sci.SetSel(start+5, start+5); return; } } if (autoIndent) { // get last non-empty line string text = ""; int line2 = line-1; while (line2 >= 0 && text.Length == 0) { text = sci.GetLine(line2).TrimEnd(); line2--; } if ((text.EndsWith(">") && !text.EndsWith("?>") && !text.EndsWith("%>") && !re_closingTag.IsMatch(text)) || text.EndsWith("<!--") || text.EndsWith("<![CDATA[")) { // get the previous tag do { position--; c = (char)sci.CharAt(position); } while (position > 0 && c != '>'); ctag = GetXMLContextTag(sci, position); if ((char)sci.CharAt(position-1) == '/') return; // insert blank line if we pressed Enter between a tag & it's closing tag int indent = sci.GetLineIndentation(line2+1); string checkStart = null; if (text.EndsWith("<!--")) checkStart = "-->"; else if (text.EndsWith("<![CDATA[")) checkStart = "]]>"; else if (ctag.Name != null) checkStart = "</"+ctag.Name; if (checkStart != null) { text = sci.GetLine(line).TrimStart(); if (text.StartsWith(checkStart)) { sci.SetLineIndentation(line, indent); sci.InsertText(sci.PositionFromLine(line), mainForm.GetNewLineMarker(sci.EOLMode)); } } // indent sci.SetLineIndentation(line, indent+sci.Indent); position = sci.LineIndentPosition(line); sci.SetSel(position, position); return; } } break; case '<': case '/': if (value == '/') { if ((position < 2) || ((char)sci.CharAt(position-2) != '<')) return; } else { ctag = GetXMLContextTag(sci, position); if (ctag.Tag != null) return; } // new tag if (enableHtmlCompletion && cType == XMLType.Known) { ArrayList items = new ArrayList(); string previous = null; foreach(HTMLTag tag in knownTags) if (tag.Name != previous) { items.Add( new HtmlTagItem(tag.Name, tag.Tag) ); previous = tag.Name; } CompletionList.Show(items, true); } else { // allow another plugin to handle this mainForm.DispatchEvent(new DataEvent(EventType.CustomData,"XMLCompletion.Element",new XMLContextTag())); } return; case '>': if (autoCloseTags) { ctag = GetXMLContextTag(sci, position); if (ctag.Name != null && !ctag.Tag.EndsWith("/>")) { // est-ce un tag sans enfant? bool isLeaf = false; if (cType == XMLType.Known) foreach(HTMLTag tag in knownTags) { if (String.Compare(tag.Tag, ctag.Name, true) == 0) { isLeaf = tag.IsLeaf; break; } } if (isLeaf) { sci.SetSel(position-1,position); sci.ReplaceSel("/>"); sci.SetSel(position+1, position+1); } else { string closeTag = "</"+ctag.Name+">"; sci.ReplaceSel(closeTag); sci.SetSel(position, position); } } } return; case ' ': c = (char)sci.CharAt(position); if (c > 32 && c != '/' && c != '>' && c != '<') return; ctag = GetXMLContextTag(sci, position); if (ctag.Tag != null) { if (InQuotes(ctag.Tag) || ctag.Tag.LastIndexOf('"') < ctag.Tag.LastIndexOf('=')) return; // if (enableHtmlCompletion && cType == XMLType.Known) { foreach(HTMLTag tag in knownTags) if (String.Compare(tag.Tag, ctag.Name, true) == 0) { ArrayList items = new ArrayList(); string previous = null; foreach(string attr in tag.Attributes) if (attr != previous) { items.Add( new HtmlAttributeItem(attr) ); previous = attr; } CompletionList.Show(items, true); return; } } else { // allow another plugin to handle this object[] o = new object[]{ctag,""}; mainForm.DispatchEvent(new DataEvent(EventType.CustomData,"XMLCompletion.Attribute",o)); } } return; case '=': if (insertQuotes) { ctag = GetXMLContextTag(sci, position); position = sci.CurrentPos-2; if (ctag.Tag != null && !InQuotes(ctag.Tag) && (GetWordLeft(sci, ref position).Length > 0)) { position = sci.CurrentPos; c = (char)sci.CharAt(position); if (c > 32 && c != '>') sci.ReplaceSel("\"\" "); else sci.ReplaceSel("\"\""); sci.SetSel(position+1, position+1); } } return; case '?': case '%': if (autoCloseTags && position > 1) { ctag = GetXMLContextTag(sci, position-2); if (ctag.Tag == null || ctag.Tag.EndsWith(">")) { if ((char)sci.CharAt(position-2) == '<') { sci.ReplaceSel((char)value + ">"); sci.SetSel(position, position); } } } break; case '!': if (autoCloseTags && position > 1) { ctag = GetXMLContextTag(sci, position-2); if (ctag.Tag == null || ctag.Tag.EndsWith(">")) { if ((char)sci.CharAt(position-2) == '<') { CompletionList.Show(xmlBlocks, true); } } } break; } }
public void Execute() { Sci = PluginBase.MainForm.CurrentDocument.SciControl; Sci.BeginUndoAction(); try { IASContext context = ASContext.Context; string selection = Sci.SelText; if (selection == null || selection.Length == 0) { return; } if (selection.TrimStart().Length == 0) { return; } Sci.SetSel(Sci.SelectionStart + selection.Length - selection.TrimStart().Length, Sci.SelectionEnd); Sci.CurrentPos = Sci.SelectionEnd; Int32 pos = Sci.CurrentPos; int lineStart = Sci.LineFromPosition(Sci.SelectionStart); int lineEnd = Sci.LineFromPosition(Sci.SelectionEnd); int firstLineIndent = Sci.GetLineIndentation(lineStart); int entryPointIndent = Sci.Indent; for (int i = lineStart; i <= lineEnd; i++) { int indent = Sci.GetLineIndentation(i); if (i > lineStart) { Sci.SetLineIndentation(i, indent - firstLineIndent + entryPointIndent); } } string selText = Sci.SelText; Sci.ReplaceSel(NewName + "();"); cFile = ASContext.Context.CurrentModel; ASFileParser parser = new ASFileParser(); parser.ParseSrc(cFile, Sci.Text); bool isAs3 = cFile.Context.Settings.LanguageId == "AS3"; FoundDeclaration found = GetDeclarationAtLine(Sci, lineStart); if (found == null || found.member == null) { return; } int position = Sci.PositionFromLine(found.member.LineTo + 1) - ((Sci.EOLMode == 0) ? 2 : 1); Sci.SetSel(position, position); StringBuilder sb = new StringBuilder(); sb.Append("$(Boundary)\n\n"); if ((found.member.Flags & FlagType.Static) > 0) { sb.Append("static "); } sb.Append(ASGenerator.GetPrivateKeyword()); sb.Append(" function "); sb.Append(NewName); sb.Append("():"); sb.Append(isAs3 ? "void " : "Void "); sb.Append("$(CSLB){\n\t"); sb.Append(selText); sb.Append("$(EntryPoint)"); sb.Append("\n}\n$(Boundary)"); ASGenerator.InsertCode(position, sb.ToString()); } finally { Sci.EndUndoAction(); } }
public static void GenerateExtractVariable(ScintillaControl sci, string newName) { string expression = sci.SelText.Trim(new char[] { '=', ' ', '\t', '\n', '\r', ';', '.' }); expression = expression.TrimEnd(new char[] { '(', '[', '{', '<' }); expression = expression.TrimStart(new char[] { ')', ']', '}', '>' }); var cFile = ASContext.Context.CurrentModel; ASFileParser parser = new ASFileParser(); parser.ParseSrc(cFile, sci.Text); MemberModel current = cFile.Context.CurrentMember; string characterClass = ScintillaControl.Configuration.GetLanguage(sci.ConfigurationLanguage).characterclass.Characters; int funcBodyStart = GetBodyStart(current.LineFrom, current.LineTo, sci); sci.SetSel(funcBodyStart, sci.LineEndPosition(current.LineTo)); string currentMethodBody = sci.SelText; var insertPosition = funcBodyStart + currentMethodBody.IndexOfOrdinal(expression); var line = sci.LineFromPosition(insertPosition); insertPosition = sci.LineIndentPosition(line); int lastPos = -1; sci.Colourise(0, -1); while (true) { lastPos = currentMethodBody.IndexOfOrdinal(expression, lastPos + 1); if (lastPos > -1) { char prevOrNextChar; if (lastPos > 0) { prevOrNextChar = currentMethodBody[lastPos - 1]; if (characterClass.IndexOf(prevOrNextChar) > -1) { continue; } } if (lastPos + expression.Length < currentMethodBody.Length) { prevOrNextChar = currentMethodBody[lastPos + expression.Length]; if (characterClass.IndexOf(prevOrNextChar) > -1) { continue; } } var pos = funcBodyStart + lastPos; int style = sci.BaseStyleAt(pos); if (ASComplete.IsCommentStyle(style)) continue; sci.SetSel(pos, pos + expression.Length); sci.ReplaceSel(newName); currentMethodBody = currentMethodBody.Substring(0, lastPos) + newName + currentMethodBody.Substring(lastPos + expression.Length); lastPos += newName.Length; } else { break; } } sci.CurrentPos = insertPosition; sci.SetSel(sci.CurrentPos, sci.CurrentPos); MemberModel m = new MemberModel(newName, "", FlagType.LocalVar, 0); m.Value = expression; string snippet = TemplateUtils.GetTemplate("Variable"); snippet = TemplateUtils.ReplaceTemplateVariable(snippet, "Modifiers", null); snippet = TemplateUtils.ToDeclarationString(m, snippet); snippet += NewLine + "$(Boundary)"; SnippetHelper.InsertSnippetText(sci, sci.CurrentPos, snippet); }
private static void GenerateVariableJob(GeneratorJobType job, ScintillaControl sci, MemberModel member, bool detach, ClassModel inClass) { var position = 0; bool isOtherClass = false; Visibility visibility = job.Equals(GeneratorJobType.Variable) ? GetDefaultVisibility(inClass) : Visibility.Public; FlagType kind = job.Equals(GeneratorJobType.Constant) ? FlagType.Constant : FlagType.Variable; // evaluate, if the variable (or constant) should be generated in other class ASResult varResult = ASComplete.GetExpressionType(sci, sci.WordEndPosition(sci.CurrentPos, true)); var memberIsStatic = member != null && (member.Flags & FlagType.Static) > 0; var dot = ASContext.Context.Features.dot; if (ASContext.CommonSettings.GenerateScope && !varResult.Context.Value.Contains(dot)) { position = sci.CurrentPos; var start = sci.WordStartPosition(position, true); var length = sci.MBSafeTextLength(contextToken); sci.SetSel(start, start + length); var scope = memberIsStatic ? inClass.QualifiedName : "this"; var text = scope + dot + contextToken; sci.ReplaceSel(text); UpdateLookupPosition(position, text.Length - length); } int contextOwnerPos = GetContextOwnerEndPos(sci, sci.WordStartPosition(sci.CurrentPos, true)); MemberModel isStatic = new MemberModel(); if (contextOwnerPos != -1) { ASResult contextOwnerResult = ASComplete.GetExpressionType(sci, contextOwnerPos); if (contextOwnerResult != null && (contextOwnerResult.Member == null || (contextOwnerResult.Member.Flags & FlagType.Constructor) > 0) && contextOwnerResult.Type != null) { isStatic.Flags |= FlagType.Static; } } else if (memberIsStatic) { isStatic.Flags |= FlagType.Static; } ASResult returnType = null; int lineNum = sci.CurrentLine; string line = sci.GetLine(lineNum); Match m = Regex.Match(line, "\\b" + Regex.Escape(contextToken) + "\\("); if (m.Success) { returnType = new ASResult(); returnType.Type = ASContext.Context.ResolveType("Function", null); } else { m = Regex.Match(line, @"=\s*[^;\n\r}}]+"); if (m.Success) { int posLineStart = sci.PositionFromLine(lineNum); if (posLineStart + m.Index >= sci.CurrentPos) { line = line.Substring(m.Index); StatementReturnType rType = GetStatementReturnType(sci, inClass, line, posLineStart + m.Index); if (rType != null) { returnType = rType.resolve; } } } } if (varResult.RelClass != null && !varResult.RelClass.IsVoid() && !varResult.RelClass.Equals(inClass)) { AddLookupPosition(); lookupPosition = -1; ASContext.MainForm.OpenEditableDocument(varResult.RelClass.InFile.FileName, false); sci = ASContext.CurSciControl; isOtherClass = true; FileModel fileModel = new FileModel(); fileModel.Context = ASContext.Context; ASFileParser parser = new ASFileParser(); parser.ParseSrc(fileModel, sci.Text); foreach (ClassModel cm in fileModel.Classes) { if (cm.QualifiedName.Equals(varResult.RelClass.QualifiedName)) { varResult.RelClass = cm; break; } } inClass = varResult.RelClass; ASContext.Context.UpdateContext(inClass.LineFrom); } var latest = GetLatestMemberForVariable(job, inClass, visibility, isStatic); // if we generate variable in current class.. if (!isOtherClass && member == null) { detach = false; lookupPosition = -1; position = sci.WordStartPosition(sci.CurrentPos, true); sci.SetSel(position, sci.WordEndPosition(position, true)); } else // if we generate variable in another class { if (latest != null) { position = FindNewVarPosition(sci, inClass, latest); } else { position = GetBodyStart(inClass.LineFrom, inClass.LineTo, sci); detach = false; } if (position <= 0) return; sci.SetSel(position, position); } // if this is a constant, we assign a value to constant string returnTypeStr = null; string eventValue = null; if (job == GeneratorJobType.Constant && returnType == null) { isStatic.Flags |= FlagType.Static; eventValue = "String = \"" + Camelize(contextToken) + "\""; } else if (returnType != null) { ClassModel inClassForImport; if (returnType.InClass != null) { inClassForImport = returnType.InClass; } else if (returnType.RelClass != null) { inClassForImport = returnType.RelClass; } else { inClassForImport = inClass; } List<string> imports = new List<string>(); if (returnType.Member != null) { if (returnType.Member.Type != ASContext.Context.Features.voidKey) { returnTypeStr = FormatType(GetShortType(returnType.Member.Type)); imports.Add(GetQualifiedType(returnType.Member.Type, inClassForImport)); } } else if (returnType != null && returnType.Type != null) { returnTypeStr = FormatType(GetShortType(returnType.Type.QualifiedName)); imports.Add(GetQualifiedType(returnType.Type.QualifiedName, inClassForImport)); } if (imports.Count > 0) { position += AddImportsByName(imports, sci.LineFromPosition(position)); sci.SetSel(position, position); } } MemberModel newMember = NewMember(contextToken, isStatic, kind, visibility); if (returnTypeStr != null) { newMember.Type = returnTypeStr; } else if (eventValue != null) { newMember.Type = eventValue; } GenerateVariable(newMember, position, detach); }
private static void GenerateFunctionJob(GeneratorJobType job, ScintillaControl sci, MemberModel member, bool detach, ClassModel inClass) { var position = 0; bool isOtherClass = false; Visibility visibility = job.Equals(GeneratorJobType.FunctionPublic) ? Visibility.Public : GetDefaultVisibility(inClass); int wordPos = sci.WordEndPosition(sci.CurrentPos, true); List<FunctionParameter> functionParameters = ParseFunctionParameters(sci, wordPos); // evaluate, if the function should be generated in other class ASResult funcResult = ASComplete.GetExpressionType(sci, sci.WordEndPosition(sci.CurrentPos, true)); var memberIsStatic = member != null && (member.Flags & FlagType.Static) > 0; var dot = ASContext.Context.Features.dot; if (ASContext.CommonSettings.GenerateScope && !funcResult.Context.Value.Contains(dot)) { position = sci.CurrentPos; var start = sci.WordStartPosition(position, true); var length = sci.MBSafeTextLength(contextToken); sci.SetSel(start, start + length); var scope = memberIsStatic ? inClass.QualifiedName : "this"; var text = scope + dot + contextToken; sci.ReplaceSel(text); UpdateLookupPosition(position, text.Length - length); } int contextOwnerPos = GetContextOwnerEndPos(sci, sci.WordStartPosition(sci.CurrentPos, true)); MemberModel isStatic = new MemberModel(); if (contextOwnerPos != -1) { ASResult contextOwnerResult = ASComplete.GetExpressionType(sci, contextOwnerPos); if (contextOwnerResult != null && (contextOwnerResult.Member == null || (contextOwnerResult.Member.Flags & FlagType.Constructor) > 0) && contextOwnerResult.Type != null) { isStatic.Flags |= FlagType.Static; } } else if (memberIsStatic) { isStatic.Flags |= FlagType.Static; } if (funcResult.RelClass != null && !funcResult.RelClass.IsVoid() && !funcResult.RelClass.Equals(inClass)) { AddLookupPosition(); lookupPosition = -1; ASContext.MainForm.OpenEditableDocument(funcResult.RelClass.InFile.FileName, true); sci = ASContext.CurSciControl; isOtherClass = true; FileModel fileModel = new FileModel(); fileModel.Context = ASContext.Context; ASFileParser parser = new ASFileParser(); parser.ParseSrc(fileModel, sci.Text); foreach (ClassModel cm in fileModel.Classes) { if (cm.QualifiedName.Equals(funcResult.RelClass.QualifiedName)) { funcResult.RelClass = cm; break; } } inClass = funcResult.RelClass; ASContext.Context.UpdateContext(inClass.LineFrom); } string blockTmpl; if ((isStatic.Flags & FlagType.Static) > 0) { blockTmpl = TemplateUtils.GetBoundary("StaticMethods"); } else if ((visibility & Visibility.Public) > 0) { blockTmpl = TemplateUtils.GetBoundary("PublicMethods"); } else { blockTmpl = TemplateUtils.GetBoundary("PrivateMethods"); } var latest = TemplateUtils.GetTemplateBlockMember(sci, blockTmpl); if (latest == null || (!isOtherClass && member == null)) { latest = GetLatestMemberForFunction(inClass, visibility, isStatic); // if we generate function in current class.. if (!isOtherClass) { MethodsGenerationLocations location = ASContext.CommonSettings.MethodsGenerationLocations; if (member == null) { detach = false; lookupPosition = -1; position = sci.WordStartPosition(sci.CurrentPos, true); sci.SetSel(position, sci.WordEndPosition(position, true)); } else if (latest != null && location == MethodsGenerationLocations.AfterSimilarAccessorMethod) { position = sci.PositionFromLine(latest.LineTo + 1) - (sci.EOLMode == 0 ? 2 : 1); sci.SetSel(position, position); } else { position = sci.PositionFromLine(member.LineTo + 1) - (sci.EOLMode == 0 ? 2 : 1); sci.SetSel(position, position); } } else // if we generate function in another class.. { if (latest != null) { position = sci.PositionFromLine(latest.LineTo + 1) - (sci.EOLMode == 0 ? 2 : 1); } else { position = GetBodyStart(inClass.LineFrom, inClass.LineTo, sci); detach = false; } sci.SetSel(position, position); } } else { position = sci.PositionFromLine(latest.LineTo + 1) - (sci.EOLMode == 0 ? 2 : 1); sci.SetSel(position, position); } // add imports to function argument types if (functionParameters.Count > 0) { List<string> typesUsed = new List<string>(); foreach (FunctionParameter parameter in functionParameters) { try { typesUsed.Add(parameter.paramQualType); } catch (Exception) { } } int o = AddImportsByName(typesUsed, sci.LineFromPosition(position)); position += o; if (latest == null) sci.SetSel(position, sci.WordEndPosition(position, true)); else sci.SetSel(position, position); } List<MemberModel> parameters = new List<MemberModel>(); foreach (FunctionParameter parameter in functionParameters) { parameters.Add(new MemberModel(parameter.paramName, parameter.paramType, FlagType.ParameterVar, 0)); } var newMember = NewMember(contextToken, isStatic, FlagType.Function, visibility); newMember.Parameters = parameters; GenerateFunction(newMember, position, detach, inClass); }
public static void GenerateExtractVariable(ScintillaControl Sci, string NewName) { FileModel cFile; string expression = Sci.SelText.Trim(new char[] { '=', ' ', '\t', '\n', '\r', ';', '.' }); expression = expression.TrimEnd(new char[] { '(', '[', '{', '<' }); expression = expression.TrimStart(new char[] { ')', ']', '}', '>' }); cFile = ASContext.Context.CurrentModel; ASFileParser parser = new ASFileParser(); parser.ParseSrc(cFile, Sci.Text); MemberModel current = cFile.Context.CurrentMember; string characterClass = ScintillaControl.Configuration.GetLanguage(Sci.ConfigurationLanguage).characterclass.Characters; int funcBodyStart = GetBodyStart(current.LineFrom, current.LineTo, Sci); Sci.SetSel(funcBodyStart, Sci.LineEndPosition(current.LineTo)); string currentMethodBody = Sci.SelText; bool isExprInSingleQuotes = (expression.StartsWith('\'') && expression.EndsWith('\'')); bool isExprInDoubleQuotes = (expression.StartsWith('\"') && expression.EndsWith('\"')); int stylemask = (1 << Sci.StyleBits) - 1; int lastPos = -1; char prevOrNextChar; Sci.Colourise(0, -1); while (true) { lastPos = currentMethodBody.IndexOfOrdinal(expression, lastPos + 1); if (lastPos > -1) { if (lastPos > 0) { prevOrNextChar = currentMethodBody[lastPos - 1]; if (characterClass.IndexOf(prevOrNextChar) > -1) { continue; } } if (lastPos + expression.Length < currentMethodBody.Length) { prevOrNextChar = currentMethodBody[lastPos + expression.Length]; if (characterClass.IndexOf(prevOrNextChar) > -1) { continue; } } int style = Sci.StyleAt(funcBodyStart + lastPos) & stylemask; if (ASComplete.IsCommentStyle(style)) { continue; } else if ((isExprInDoubleQuotes && currentMethodBody[lastPos] == '"' && currentMethodBody[lastPos + expression.Length - 1] == '"') || (isExprInSingleQuotes && currentMethodBody[lastPos] == '\'' && currentMethodBody[lastPos + expression.Length - 1] == '\'')) { } else if (!ASComplete.IsTextStyle(style)) { continue; } Sci.SetSel(funcBodyStart + lastPos, funcBodyStart + lastPos + expression.Length); Sci.ReplaceSel(NewName); currentMethodBody = currentMethodBody.Substring(0, lastPos) + NewName + currentMethodBody.Substring(lastPos + expression.Length); lastPos += NewName.Length; } else { break; } } Sci.CurrentPos = funcBodyStart; Sci.SetSel(Sci.CurrentPos, Sci.CurrentPos); MemberModel m = new MemberModel(NewName, "", FlagType.LocalVar, 0); m.Value = expression; string snippet = TemplateUtils.GetTemplate("Variable"); snippet = TemplateUtils.ReplaceTemplateVariable(snippet, "Modifiers", null); snippet = TemplateUtils.ToDeclarationString(m, snippet); snippet += NewLine + "$(Boundary)"; SnippetHelper.InsertSnippetText(Sci, Sci.CurrentPos, snippet); }
/// <summary> /// Handles the incoming character /// </summary> public static void OnChar(ScintillaControl sci, Int32 value) { if (cType == XMLType.Invalid || (sci.ConfigurationLanguage != "xml" && sci.ConfigurationLanguage != "html")) return; XMLContextTag ctag; Int32 position = sci.CurrentPos; if (sci.BaseStyleAt(position) == 6 && value != '"') return; // in XML attribute Char c = ' '; DataEvent de; switch (value) { case 10: // Shift+Enter to insert <BR/> Int32 line = sci.LineFromPosition(position); if (Control.ModifierKeys == Keys.Shift) { ctag = GetXMLContextTag(sci, position); if (ctag.Tag == null || ctag.Tag.EndsWith(">")) { int start = sci.PositionFromLine(line)-((sci.EOLMode == 0)? 2:1); sci.SetSel(start, position); sci.ReplaceSel((PluginSettings.UpperCaseHtmlTags) ? "<BR/>" : "<br/>"); sci.SetSel(start+5, start+5); return; } } if (PluginSettings.SmartIndenter) { // Get last non-empty line String text = ""; Int32 line2 = line - 1; while (line2 >= 0 && text.Length == 0) { text = sci.GetLine(line2).TrimEnd(); line2--; } if ((text.EndsWith(">") && !text.EndsWith("?>") && !text.EndsWith("%>") && !closingTag.IsMatch(text)) || text.EndsWith("<!--") || text.EndsWith("<![CDATA[")) { // Get the previous tag do { position--; c = (Char)sci.CharAt(position); } while (position > 0 && c != '>'); ctag = GetXMLContextTag(sci, c == '>' ? position + 1 : position); if ((Char)sci.CharAt(position-1) == '/') return; // Insert blank line if we pressed Enter between a tag & it's closing tag Int32 indent = sci.GetLineIndentation(line2 + 1); String checkStart = null; bool subIndent = true; if (text.EndsWith("<!--")) { checkStart = "-->"; subIndent = false; } else if (text.EndsWith("<![CDATA[")) { checkStart = "]]>"; subIndent = false; } else if (ctag.Closed) subIndent = false; else if (ctag.Name != null) { checkStart = "</" + ctag.Name; if (ctag.Name.ToLower() == "script" || ctag.Name.ToLower() == "style") subIndent = false; if (ctag.Tag.IndexOf('\r') > 0 || ctag.Tag.IndexOf('\n') > 0) subIndent = false; } if (checkStart != null) { text = sci.GetLine(line).TrimStart(); if (text.StartsWith(checkStart)) { sci.SetLineIndentation(line, indent); sci.InsertText(sci.PositionFromLine(line), LineEndDetector.GetNewLineMarker(sci.EOLMode)); } } // Indent the code if (subIndent) indent += sci.Indent; sci.SetLineIndentation(line, indent); position = sci.LineIndentPosition(line); sci.SetSel(position, position); return; } } break; case '<': case '/': if (value == '/') { if ((position < 2) || ((Char)sci.CharAt(position-2) != '<')) return; ctag = new XMLContextTag(); ctag.Closing = true; } else { ctag = GetXMLContextTag(sci, position); if (ctag.Tag != null) return; } // Allow another plugin to handle this de = new DataEvent(EventType.Command, "XMLCompletion.Element", ctag); EventManager.DispatchEvent(PluginBase.MainForm, de); if (de.Handled) return; // New tag if (PluginSettings.EnableXMLCompletion && cType == XMLType.Known) { List<ICompletionListItem> items = new List<ICompletionListItem>(); String previous = null; foreach (string ns in namespaces) { items.Add(new NamespaceItem(ns)); } foreach (HTMLTag tag in knownTags) if (tag.Name != previous && (tag.NS == "" || tag.NS == defaultNS)) { items.Add( new HtmlTagItem(tag.Name, tag.Tag)); previous = tag.Name; } items.Sort(new ListItemComparer()); CompletionList.Show(items, true); } return; case ':': ctag = GetXMLContextTag(sci, position); if (ctag.NameSpace == null || position - ctag.Position > ctag.Name.Length + 2) return; // Allow another plugin to handle this de = new DataEvent(EventType.Command, "XMLCompletion.Namespace", ctag); EventManager.DispatchEvent(PluginBase.MainForm, de); if (de.Handled) return; // Show namespace's tags if (PluginSettings.EnableXMLCompletion && cType == XMLType.Known) { List<ICompletionListItem> items = new List<ICompletionListItem>(); String previous = null; foreach (HTMLTag tag in knownTags) if (tag.Name != previous && tag.NS == ctag.NameSpace) { items.Add(new HtmlTagItem(tag.Name, tag.Name)); previous = tag.Name; } CompletionList.Show(items, true); } return; case '>': if (PluginSettings.CloseTags) { ctag = GetXMLContextTag(sci, position); if (ctag.Name != null && !ctag.Closed) { // Allow another plugin to handle this de = new DataEvent(EventType.Command, "XMLCompletion.CloseElement", ctag); EventManager.DispatchEvent(PluginBase.MainForm, de); if (de.Handled) return; if (ctag.Closing) return; Boolean isLeaf = false; if (cType == XMLType.Known) foreach(HTMLTag tag in knownTags) { if (String.Compare(tag.Tag, ctag.Name, true) == 0) { isLeaf = tag.IsLeaf; break; } } if (isLeaf) { sci.SetSel(position-1,position); sci.ReplaceSel("/>"); sci.SetSel(position+1, position+1); } else { String closeTag = "</"+ctag.Name+">"; sci.ReplaceSel(closeTag); sci.SetSel(position, position); } } } return; case ' ': c = (char)sci.CharAt(position); if (c > 32 && c != '/' && c != '>' && c != '<') return; ctag = GetXMLContextTag(sci, position); if (ctag.Tag != null) { if (InQuotes(ctag.Tag) || ctag.Tag.LastIndexOf('"') < ctag.Tag.LastIndexOf('=')) return; // Allow another plugin to handle this Object[] obj = new Object[] { ctag, "" }; de = new DataEvent(EventType.Command, "XMLCompletion.Attribute", obj); EventManager.DispatchEvent(PluginBase.MainForm, de); if (de.Handled) return; if (PluginSettings.EnableXMLCompletion && cType == XMLType.Known) { foreach (HTMLTag tag in knownTags) if (String.Compare(tag.Tag, ctag.Name, true) == 0) { List<ICompletionListItem> items = new List<ICompletionListItem>(); String previous = null; foreach (String attr in tag.Attributes) if (attr != previous) { items.Add(new HtmlAttributeItem(attr)); previous = attr; } CompletionList.Show(items, true); return; } } } /*else { if (Control.ModifierKeys == Keys.Shift) { sci.SetSel(position - 1, position); sci.ReplaceSel(" "); } }*/ return; case '=': if (PluginSettings.InsertQuotes) { ctag = GetXMLContextTag(sci, position); position = sci.CurrentPos-2; if (ctag.Tag != null && !ctag.Tag.StartsWith("<!") && !InQuotes(ctag.Tag) && (GetWordLeft(sci, ref position).Length > 0)) { position = sci.CurrentPos; c = (Char)sci.CharAt(position); if (c > 32 && c != '>') sci.ReplaceSel("\"\" "); else sci.ReplaceSel("\"\""); sci.SetSel(position+1, position+1); justInsertedQuotesAt = position+1; // Allow another plugin to handle this de = new DataEvent(EventType.Command, "XMLCompletion.AttributeValue", new XMLContextTag()); EventManager.DispatchEvent(PluginBase.MainForm, de); } } return; case '"': ctag = GetXMLContextTag(sci, position); if (position > 1 && ctag.Tag != null && !ctag.Tag.StartsWith("<!")) { // TODO Colorize text change to highlight what's been done if (justInsertedQuotesAt == position - 1) { justInsertedQuotesAt = -1; c = (Char)sci.CharAt(position - 2); if (c == '"' && (Char)sci.CharAt(position-2) == '"') { sci.SetSel(position - 2, position); sci.ReplaceSel("\""); } // Allow another plugin to handle this de = new DataEvent(EventType.Command, "XMLCompletion.AttributeValue", new XMLContextTag()); EventManager.DispatchEvent(PluginBase.MainForm, de); } else { c = (Char)sci.CharAt(position - 1); if (c == '"' && (Char)sci.CharAt(position) == '"') { sci.SetSel(position - 1, position + 1); sci.ReplaceSel("\""); } } } break; case '?': case '%': if (PluginSettings.CloseTags && position > 1) { ctag = GetXMLContextTag(sci, position-2); if (ctag.Tag == null || ctag.Tag.EndsWith(">")) { if ((Char)sci.CharAt(position-2) == '<') { sci.ReplaceSel((Char)value + ">"); sci.SetSel(position, position); } } } break; case '!': if (PluginSettings.CloseTags && position > 1) { ctag = GetXMLContextTag(sci, position-2); if (ctag.Tag == null || ctag.Tag.EndsWith(">")) { if ((Char)sci.CharAt(position-2) == '<') { CompletionList.Show(xmlBlocks, true); } } } break; } }
private static bool RemoveOneLocalDeclaration(ScintillaControl sci, MemberModel contextMember) { string type = ""; if (contextMember.Type != null && (contextMember.Flags & FlagType.Inferred) == 0) { type = FormatType(contextMember.Type); if (type.IndexOf('*') > 0) type = type.Replace("/*", @"/\*\s*").Replace("*/", @"\s*\*/"); type = @":\s*" + type; } Regex reDecl = new Regex(String.Format(@"[\s\(]((var|const)\s+{0}\s*{1})\s*", contextMember.Name, type)); for (int i = contextMember.LineFrom; i <= contextMember.LineTo + 10; i++) { string text = sci.GetLine(i); Match m = reDecl.Match(text); if (m.Success) { int index = sci.MBSafeTextLength(text.Substring(0, m.Groups[1].Index)); int position = sci.PositionFromLine(i) + index; int len = sci.MBSafeTextLength(m.Groups[1].Value); sci.SetSel(position, position + len); if (contextMember.Type == null || (contextMember.Flags & FlagType.Inferred) != 0) sci.ReplaceSel(contextMember.Name + " "); else sci.ReplaceSel(contextMember.Name); UpdateLookupPosition(position, contextMember.Name.Length - len); return true; } } return false; }
static public void ReplaceText(ScintillaControl sci, string tail) { if (InfoTip.CallTipActive) { InfoTip.Hide(); return; } if (completionList.SelectedIndex >= 0) { ICompletionListItem item = (ICompletionListItem)completionList.Items[completionList.SelectedIndex]; sci.SetSel(startPos, sci.CurrentPos); string replace = item.Value; if (replace != null) sci.ReplaceSel(replace+tail); } Hide(); }
public static bool RenameMember(ScintillaControl Sci, MemberModel member, string newName) { ContextFeatures features = ASContext.Context.Features; string kind = features.varKey; if ((member.Flags & FlagType.Getter) > 0) kind = features.getKey; else if ((member.Flags & FlagType.Setter) > 0) kind = features.setKey; else if (member.Flags == FlagType.Function) kind = features.functionKey; Regex reMember = new Regex(String.Format(@"{0}\s+({1})[\s:]", kind, member.Name)); string line; Match m; int index, position; for (int i = member.LineFrom; i <= member.LineTo; i++) { line = Sci.GetLine(i); m = reMember.Match(line); if (m.Success) { index = Sci.MBSafeTextLength(line.Substring(0, m.Groups[1].Index)); position = Sci.PositionFromLine(i) + index; Sci.SetSel(position, position + member.Name.Length); Sci.ReplaceSel(newName); UpdateLookupPosition(position, 1); return true; } } return false; }
public void Execute() { Sci = PluginBase.MainForm.CurrentDocument.SciControl; Sci.BeginUndoAction(); try { IASContext context = ASContext.Context; Int32 pos = Sci.CurrentPos; string expression = Sci.SelText.Trim(new char[] { '=', ' ', '\t', '\n', '\r', ';', '.' }); expression = expression.TrimEnd(new char[] { '(', '[', '{', '<' }); expression = expression.TrimStart(new char[] { ')', ']', '}', '>' }); cFile = ASContext.Context.CurrentModel; ASFileParser parser = new ASFileParser(); parser.ParseSrc(cFile, Sci.Text); MemberModel current = cFile.Context.CurrentMember; string characterClass = ScintillaControl.Configuration.GetLanguage(Sci.ConfigurationLanguage).characterclass.Characters; int funcBodyStart = ASGenerator.GetBodyStart(current.LineFrom, current.LineTo, Sci); Sci.SetSel(funcBodyStart, Sci.LineEndPosition(current.LineTo)); string currentMethodBody = Sci.SelText; bool isExprInSingleQuotes = (expression.StartsWith("'") && expression.EndsWith("'")); bool isExprInDoubleQuotes = (expression.StartsWith("\"") && expression.EndsWith("\"")); int stylemask = (1 << Sci.StyleBits) - 1; int lastPos = -1; char prevOrNextChar; Sci.Colourise(0, -1); while (true) { lastPos = currentMethodBody.IndexOf(expression, lastPos + 1); if (lastPos > -1) { if (lastPos > 0) { prevOrNextChar = currentMethodBody[lastPos - 1]; if (characterClass.IndexOf(prevOrNextChar) > -1) { continue; } } if (lastPos + expression.Length < currentMethodBody.Length) { prevOrNextChar = currentMethodBody[lastPos + expression.Length]; if (characterClass.IndexOf(prevOrNextChar) > -1) { continue; } } int style = Sci.StyleAt(funcBodyStart + lastPos) & stylemask; if (ASComplete.IsCommentStyle(style)) { continue; } else if ((isExprInDoubleQuotes && currentMethodBody[lastPos] == '"' && currentMethodBody[lastPos + expression.Length - 1] == '"') || (isExprInSingleQuotes && currentMethodBody[lastPos] == '\'' && currentMethodBody[lastPos + expression.Length - 1] == '\'')) { } else if (!ASComplete.IsTextStyle(style)) { continue; } Sci.SetSel(funcBodyStart + lastPos, funcBodyStart + lastPos + expression.Length); Sci.ReplaceSel(NewName); currentMethodBody = currentMethodBody.Substring(0, lastPos) + NewName + currentMethodBody.Substring(lastPos + expression.Length); lastPos += NewName.Length; } else { break; } } Sci.CurrentPos = funcBodyStart; Sci.SetSel(Sci.CurrentPos, Sci.CurrentPos); string snippet = "var " + NewName + ":$(EntryPoint) = " + expression + ";\n$(Boundary)"; SnippetHelper.InsertSnippetText(Sci, Sci.CurrentPos, snippet); } finally { Sci.EndUndoAction(); } }
/// <summary> /// Replaces only the matches in the current sci control /// </summary> public static void ReplaceMatches(IList<SearchMatch> matches, ScintillaControl sci, String replacement, String src) { if (sci == null || matches == null || matches.Count == 0) return; sci.BeginUndoAction(); try { for (Int32 i = 0; i < matches.Count; i++) { SelectMatch(sci, matches[i]); FRSearch.PadIndexes((List<SearchMatch>)matches, i, matches[i].Value, replacement); sci.EnsureVisible(sci.LineFromPosition(sci.MBSafePosition(matches[i].Index))); sci.ReplaceSel(replacement); } } finally { sci.EndUndoAction(); } }
private static void ConvertToConst(ClassModel inClass, ScintillaControl Sci, MemberModel member, bool detach) { String suggestion = "NEW_CONST"; String label = TextHelper.GetString("ASCompletion.Label.ConstName"); String title = TextHelper.GetString("ASCompletion.Title.ConvertToConst"); Hashtable info = new Hashtable(); info["suggestion"] = suggestion; info["label"] = label; info["title"] = title; DataEvent de = new DataEvent(EventType.Command, "ProjectManager.LineEntryDialog", info); EventManager.DispatchEvent(null, de); if (!de.Handled) return; suggestion = (string)info["suggestion"]; int position = Sci.CurrentPos; MemberModel latest = null; int wordPosEnd = Sci.WordEndPosition(position, true); int wordPosStart = Sci.WordStartPosition(position, true); char cr = (char)Sci.CharAt(wordPosEnd); if (cr == '.') { wordPosEnd = Sci.WordEndPosition(wordPosEnd + 1, true); } else { cr = (char)Sci.CharAt(wordPosStart - 1); if (cr == '.') { wordPosStart = Sci.WordStartPosition(wordPosStart - 1, true); } } Sci.SetSel(wordPosStart, wordPosEnd); string word = Sci.SelText; Sci.ReplaceSel(suggestion); if (member == null) { detach = false; lookupPosition = -1; position = Sci.WordStartPosition(Sci.CurrentPos, true); Sci.SetSel(position, Sci.WordEndPosition(position, true)); } else { latest = GetLatestMemberForVariable(GeneratorJobType.Constant, inClass, Visibility.Private, new MemberModel("", "", FlagType.Static, 0)); if (latest != null) { position = FindNewVarPosition(Sci, inClass, latest); } else { position = GetBodyStart(inClass.LineFrom, inClass.LineTo, Sci); detach = false; } if (position <= 0) return; Sci.SetSel(position, position); } MemberModel m = NewMember(suggestion, member, FlagType.Variable | FlagType.Constant | FlagType.Static); m.Type = ASContext.Context.Features.numberKey; m.Value = word; GenerateVariable(m, position, detach); }