/// <summary> /// Processes the snippet and template arguments /// </summary> public static Int32 PostProcessSnippets(ScintillaNet.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.IndexOf(ENTRYPOINT)); Int32 exitPosition = sci.MBSafePosition(text.IndexOf(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 GenerateDefaultHandlerName(ScintillaNet.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)"); else InsertCode(position, contextToken); 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 RenameMember(ScintillaNet.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 static bool MakePrivate(ScintillaNet.ScintillaControl Sci, MemberModel member) { ContextFeatures features = ASContext.Context.Features; string visibility = GetPrivateKeyword(); 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; }
private static bool RemoveOneLocalDeclaration(ScintillaNet.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; }
public static void GenerateExtractVariable(ScintillaNet.ScintillaControl Sci, string NewName) { FileModel cFile; 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 = ScintillaNet.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); 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 ConvertToConst(ClassModel inClass, ScintillaNet.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); }
private static void ChangeMethodDecl(ScintillaNet.ScintillaControl Sci, MemberModel member, ClassModel inClass) { int wordPos = Sci.WordEndPosition(Sci.CurrentPos, true); List<FunctionParameter> functionParameters = ParseFunctionParameters(Sci, wordPos); ASResult funcResult = ASComplete.GetExpressionType(Sci, Sci.WordEndPosition(Sci.CurrentPos, true)); if (funcResult.Member == null) { return; } if (funcResult != null && funcResult.inClass != null && !funcResult.inClass.Equals(inClass)) { AddLookupPosition(); lookupPosition = -1; DockContent dc = ASContext.MainForm.OpenEditableDocument(funcResult.inClass.InFile.FileName, true); Sci = ASContext.CurSciControl; FileModel fileModel = new FileModel(); ASFileParser parser = new ASFileParser(); parser.ParseSrc(fileModel, Sci.Text); foreach (ClassModel cm in fileModel.Classes) { if (cm.QualifiedName.Equals(funcResult.inClass.QualifiedName)) { funcResult.inClass = cm; break; } } inClass = funcResult.inClass; } MemberList members = inClass.Members; foreach (MemberModel m in members) { if (m.Name == funcResult.Member.Name) { funcResult.Member = m; } } bool paramsDiffer = false; if (funcResult.Member.Parameters != null) { // check that parameters have one and the same type if (funcResult.Member.Parameters.Count == functionParameters.Count) { if (functionParameters.Count > 0) { List<MemberModel> parameters = funcResult.Member.Parameters; for (int i = 0; i < parameters.Count; i++) { MemberModel p = parameters[i]; if (p.Type != functionParameters[i].paramType) { paramsDiffer = true; break; } } } } else { paramsDiffer = true; } } // check that parameters count differs else if (functionParameters.Count != 0) { paramsDiffer = true; } if (paramsDiffer) { int app = 0; List<MemberModel> newParameters = new List<MemberModel>(); List<MemberModel> existingParameters = funcResult.Member.Parameters; for (int i = 0; i < functionParameters.Count; i++) { FunctionParameter p = functionParameters[i]; if (existingParameters != null && existingParameters.Count > (i - app) && existingParameters[i - app].Type == p.paramType) { newParameters.Add(existingParameters[i - app]); } else { if (existingParameters != null && existingParameters.Count < functionParameters.Count) { app++; } newParameters.Add(new MemberModel(p.param, p.paramType, FlagType.ParameterVar, 0)); } } funcResult.Member.Parameters = newParameters; int posStart = Sci.PositionFromLine(funcResult.Member.LineFrom); int posEnd = Sci.LineEndPosition(funcResult.Member.LineTo); Sci.SetSel(posStart, posEnd); string selectedText = Sci.SelText; Regex rStart = new Regex(String.Format(@"\s+{0}\s*\(([^\)]*)\)(\s*:\s*([^({{|\n|\r|\s|;)]+))?", funcResult.Member.Name)); Match mStart = rStart.Match(selectedText); if (!mStart.Success) { return; } int start = mStart.Index + posStart; int end = start + mStart.Length; Sci.SetSel(start, end); string decl = funcResult.Member.ToDeclarationString(); Sci.ReplaceSel(" " + decl); // add imports to function argument types if (functionParameters.Count > 0) { List<string> l = new List<string>(); foreach (FunctionParameter fp in functionParameters) { try { l.Add(fp.paramQualType); } catch (Exception) { } } start += AddImportsByName(l, Sci.LineFromPosition(end)); } Sci.SetSel(start, start); } }
private static void ConvertToConst(ClassModel inClass, ScintillaNet.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, "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 = FindLatest(FlagType.Constant, GetDefaultVisibility(), inClass) ?? FindLatest(FlagType.Variable, GetDefaultVisibility(), inClass); 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); } contextToken = suggestion + ":Number = " + word + ""; GenerateVariable( NewMember(contextToken, member, FlagType.Variable | FlagType.Constant | FlagType.Static), position, detach); }
/// <summary> /// Inserts the specified snippet to the document /// </summary> public static Int32 InsertSnippetText(ScintillaNet.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 private bool HandleStructureCompletion(ScintillaNet.ScintillaControl Sci) { try { int position = Sci.CurrentPos; int line = Sci.LineFromPosition(position); if (line == 0) return false; string txt = Sci.GetLine(line-1); int style = Sci.BaseStyleAt(position); int eolMode = Sci.EOLMode; // box comments if (IsCommentStyle(style) && (Sci.BaseStyleAt(position+1) == style)) { txt = txt.Trim(); if (txt.StartsWith("/*") || txt.StartsWith("*")) { Sci.ReplaceSel("* "); position = Sci.LineIndentPosition(line)+2; Sci.SetSel(position,position); return true; } } // braces else if (txt.TrimEnd().EndsWith("{") && (line > 1)) { // find matching brace int bracePos = Sci.LineEndPosition(line-1)-1; while ((bracePos > 0) && (Sci.CharAt(bracePos) != '{')) bracePos--; if (bracePos == 0 || Sci.BaseStyleAt(bracePos) != 10) return true; int match = Sci.SafeBraceMatch(bracePos); DebugConsole.Trace("match "+bracePos+" "+match); int start = line; int indent = Sci.GetLineIndentation(start-1); if (match > 0) { int endIndent = Sci.GetLineIndentation(Sci.LineFromPosition(match)); if (endIndent+Sci.TabWidth > indent) return false; } // find where to include the closing brace int startIndent = indent; int newIndent = indent+Sci.TabWidth; int count = Sci.LineCount; int lastLine = line; line++; while (line < count-1) { txt = Sci.GetLine(line).TrimEnd(); if (txt.Length != 0) { indent = Sci.GetLineIndentation(line); DebugConsole.Trace("indent "+(line+1)+" "+indent+" : "+txt); if (indent <= startIndent) break; lastLine = line; } else break; line++; } if (line >= count-1) lastLine = start; // insert closing brace DebugConsole.Trace("Insert at "+position); position = Sci.LineEndPosition(lastLine); Sci.InsertText(position, ASContext.MainForm.GetNewLineMarker(eolMode)+"}"); Sci.SetLineIndentation(lastLine+1, startIndent); return false; } } catch (Exception ex) { ErrorHandler.ShowError(ex.Message, ex); } return false; }
/// <summary> /// Some characters can fire code generation /// </summary> /// <param name="sci">Scintilla control</param> /// <param name="value">Character</param> /// <returns>Code was generated</returns> static private bool CodeAutoOnChar(ScintillaNet.ScintillaControl sci, int value) { if (!ASContext.AutoImportsEnabled) return false; int position = sci.CurrentPos; if (value == '*' && position > 1 && sci.CharAt(position-2) == '.' && LastExpression != null) { // context string key = LastExpression.Keyword; if (key != null && (key == "import" || key == "extends" || key == "implements" || key == "package")) return false; ASResult context = EvalExpression(LastExpression.Value, LastExpression, ASContext.CurrentClass, true); if (context.IsNull() || context.Class.Flags != FlagType.Package) return false; string package = LastExpression.Value; int startPos = LastExpression.Position; string check = ""; char c; while (startPos > LastExpression.PositionExpression && check.Length <= package.Length && check != package) { c = (char)sci.CharAt(--startPos); if (c > 32) check = c+check; } if (check != package) return false; // insert import string statement = "import "+package+"*;"+ASContext.MainForm.GetNewLineMarker(sci.EOLMode); int endPos = sci.CurrentPos; int line = 0; int curLine = sci.LineFromPosition(position); int firstLine = 0; bool found = false; string txt; Match mImport; while (line < curLine) { txt = sci.GetLine(line++).TrimStart(); // HACK insert imports after AS3 package declaration if (txt.StartsWith("package")) { statement = '\t'+statement; firstLine = (txt.IndexOf('{') < 0) ? line+1 : line; } else if (txt.StartsWith("import")) { found = true; // insérer dans l'ordre alphabetique mImport = ASClassParser.re_import.Match(txt); if (mImport.Success && String.Compare(mImport.Groups["package"].Value, package) > 0) { line--; break; } } else if (found) { line--; break; } } if (line == curLine) line = firstLine; position = sci.PositionFromLine(line); line = sci.FirstVisibleLine; sci.SetSel(position, position); sci.ReplaceSel(statement); // prepare insertion of the term as usual startPos += statement.Length; endPos += statement.Length; sci.SetSel(startPos, endPos); sci.ReplaceSel(""); sci.LineScroll(0, line-sci.FirstVisibleLine+1); // create classes list ASClass cClass = ASContext.CurrentClass; ArrayList list = new ArrayList(); foreach(ASMember import in cClass.Imports) if (import.Type.StartsWith(package)) list.Add(new MemberItem(import)); CompletionList.Show(list, false); return true; } return false; }