/// <summary> /// Selects a search match /// </summary> public static void SelectMatch(ScintillaControl sci, SearchMatch match) { Int32 start = sci.MBSafePosition(match.Index); // wchar to byte position Int32 end = start + sci.MBSafeTextLength(match.Value); // wchar to byte text length Int32 line = sci.LineFromPosition(start); sci.EnsureVisible(line); sci.SetSel(start, end); }
static public void sci_Modified(ScintillaControl sender, int position, int modificationType, string text, int length, int linesAdded, int line, int foldLevelNow, int foldLevelPrev) { if (linesAdded != 0) { int modline = sender.LineFromPosition(position); PluginMain.breakPointManager.UpdateBreakPoint(sender.FileName, modline, linesAdded); } }
/// <summary> /// focus a needed scientilla control and position the carret /// </summary> /// <param name="sci">a scientilla control to focus</param> /// <param name="position">position of the carret in the text</param> /// <param name="length"></param> public void GotoPosAndFocus(ScintillaNet.ScintillaControl sci, int position, int length) { // don't correct to multi-byte safe position (assumed correct) int line = sci.LineFromPosition(position); //sci.EnsureVisible(line); sci.ExpandAllFolds(); sci.SetSel(position, position + length); // sci.EnsureVisible(line); int top = sci.FirstVisibleLine; int middle = top + sci.LinesOnScreen / 2; sci.LineScroll(0, line - middle); }
public void PositionControl(ScintillaControl sci) { // compute control location Point p = new Point(sci.PointXFromPosition(memberPos), sci.PointYFromPosition(memberPos)); p = ((Form)PluginBase.MainForm).PointToClient(((Control)sci).PointToScreen(p)); toolTip.Left = p.X + sci.Left; bool hasListUp = !CompletionList.Active || CompletionList.listUp; if (currentLine > sci.LineFromPosition(memberPos) || !hasListUp) toolTip.Top = p.Y - toolTip.Height + sci.Top; else toolTip.Top = p.Y + UITools.Manager.LineHeight(sci) + sci.Top; // Keep on control area if (toolTip.Right > ((Form)PluginBase.MainForm).ClientRectangle.Right) { toolTip.Left = ((Form)PluginBase.MainForm).ClientRectangle.Right - toolTip.Width; } toolTip.Show(); toolTip.BringToFront(); }
public void CallTipShow(ScintillaControl sci, int position, string text) { if (toolTip.Visible && position == memberPos && text == currentText) return; toolTip.Visible = false; currentText = text; Text = text; AutoSize(); memberPos = position; startPos = memberPos + text.IndexOf('('); currentPos = sci.CurrentPos; currentLine = sci.LineFromPosition(currentPos); PositionControl(sci); // state isActive = true; faded = false; UITools.Manager.LockControl(sci); }
/** * Provides a basic folding service and notifies * the plugins for the MarginClick event */ public void OnScintillaControlMarginClick(ScintillaControl sci, int modifiers, int position, int margin) { if (margin == 2) { int line = sci.LineFromPosition(position); sci.ToggleFold(line); } }
/// <summary> /// Provides a basic folding service and notifies the plugins for the MarginClick event /// </summary> public void OnScintillaControlMarginClick(ScintillaControl sci, Int32 modifiers, Int32 position, Int32 margin) { if (margin == 2) { Int32 line = sci.LineFromPosition(position); if (Control.ModifierKeys == Keys.Control) MarkerManager.ToggleMarker(sci, 0, line); else sci.ToggleFold(line); } }
/// <summary> /// Refreshes the statusbar display and updates the important edit buttons /// </summary> public void OnScintillaControlUpdateControl(ScintillaControl sci) { if (this.InvokeRequired) { this.BeginInvoke((MethodInvoker)delegate { this.OnScintillaControlUpdateControl(sci); }); return; } ITabbedDocument document = DocumentManager.FindDocument(sci); if (sci != null && document != null && document.IsEditable) { Int32 column = sci.Column(sci.CurrentPos) + 1; Int32 line = sci.LineFromPosition(sci.CurrentPos) + 1; String statusText = " " + TextHelper.GetString("Info.StatusText"); String file = PathHelper.GetCompactPath(sci.FileName); String eol = (sci.EOLMode == 0) ? "CR+LF" : ((sci.EOLMode == 1) ? "CR" : "LF"); String encoding = ButtonManager.GetActiveEncodingName(); this.toolStripStatusLabel.Text = String.Format(statusText, line, column, eol, encoding, file); } else this.toolStripStatusLabel.Text = " "; this.OnUpdateMainFormDialogTitle(); ButtonManager.UpdateFlaggedButtons(); NotifyEvent ne = new NotifyEvent(EventType.UIRefresh); EventManager.DispatchEvent(this, ne); }
/// <summary> /// Move the document position /// </summary> private void MoveToPosition(ScintillaControl sci, Int32 position) { try { position = sci.MBSafePosition(position); // scintilla indexes are in 8bits Int32 line = sci.LineFromPosition(position); sci.EnsureVisible(line); sci.GotoPos(position); sci.SetSel(position, sci.LineEndPosition(line)); sci.Focus(); } catch { String message = TextHelper.GetString("Info.InvalidItem"); ErrorManager.ShowInfo(message); this.RemoveInvalidItems(); this.RefreshProject(); } }
private static void AddLookupPosition(ScintillaControl sci) { if (lookupPosition >= 0 && sci != null) { int lookupLine = sci.LineFromPosition(lookupPosition); int lookupCol = lookupPosition - sci.PositionFromLine(lookupLine); // TODO: Refactor, doesn't make a lot of sense to have this feature inside the Panel ASContext.Panel.SetLastLookupPosition(sci.FileName, lookupLine, lookupCol); } }
static public void GenerateOverride(ScintillaControl Sci, ClassModel ofClass, MemberModel member, int position) { ContextFeatures features = ASContext.Context.Features; List<string> typesUsed = new List<string>(); bool isProxy = (member.Namespace == "flash_proxy"); if (isProxy) typesUsed.Add("flash.utils.flash_proxy"); bool isAS2Event = ASContext.Context.Settings.LanguageId == "AS2" && member.Name.StartsWithOrdinal("on"); bool isObjectMethod = ofClass.QualifiedName == "Object"; int line = Sci.LineFromPosition(position); string currentText = Sci.GetLine(line); int startPos = currentText.Length; GetStartPos(currentText, ref startPos, features.privateKey); GetStartPos(currentText, ref startPos, features.protectedKey); GetStartPos(currentText, ref startPos, features.internalKey); GetStartPos(currentText, ref startPos, features.publicKey); GetStartPos(currentText, ref startPos, features.staticKey); GetStartPos(currentText, ref startPos, features.overrideKey); startPos += Sci.PositionFromLine(line); FlagType flags = member.Flags; string acc = ""; string decl = ""; if (features.hasNamespaces && !string.IsNullOrEmpty(member.Namespace) && member.Namespace != "internal") acc = member.Namespace; else if ((member.Access & Visibility.Public) > 0) acc = features.publicKey; else if ((member.Access & Visibility.Internal) > 0) acc = features.internalKey; else if ((member.Access & Visibility.Protected) > 0) acc = features.protectedKey; else if ((member.Access & Visibility.Private) > 0 && features.methodModifierDefault != Visibility.Private) acc = features.privateKey; bool isStatic = (flags & FlagType.Static) > 0; if (isStatic) acc = features.staticKey + " " + acc; if (!isAS2Event && !isObjectMethod) acc = features.overrideKey + " " + acc; acc = Regex.Replace(acc, "[ ]+", " ").Trim(); if ((flags & (FlagType.Getter | FlagType.Setter)) > 0) { string type = member.Type; string name = member.Name; if (member.Parameters != null && member.Parameters.Count == 1) type = member.Parameters[0].Type; type = FormatType(type); if (type == null && !features.hasInference) type = features.objectKey; bool genGetter = ofClass.Members.Search(name, FlagType.Getter, 0) != null; bool genSetter = ofClass.Members.Search(name, FlagType.Setter, 0) != null; if (IsHaxe) { // property is public but not the methods acc = features.overrideKey; } if (genGetter) { string tpl = TemplateUtils.GetTemplate("OverrideGetter", "Getter"); tpl = TemplateUtils.ReplaceTemplateVariable(tpl, "Modifiers", acc); tpl = TemplateUtils.ReplaceTemplateVariable(tpl, "Name", name); tpl = TemplateUtils.ReplaceTemplateVariable(tpl, "Type", type); tpl = TemplateUtils.ReplaceTemplateVariable(tpl, "Member", "super." + name); decl += tpl; } if (genSetter) { string tpl = TemplateUtils.GetTemplate("OverrideSetter", "Setter"); tpl = TemplateUtils.ReplaceTemplateVariable(tpl, "Modifiers", acc); tpl = TemplateUtils.ReplaceTemplateVariable(tpl, "Name", name); tpl = TemplateUtils.ReplaceTemplateVariable(tpl, "Type", type); tpl = TemplateUtils.ReplaceTemplateVariable(tpl, "Member", "super." + name); tpl = TemplateUtils.ReplaceTemplateVariable(tpl, "Void", ASContext.Context.Features.voidKey ?? "void"); if (decl.Length > 0) { tpl = "\n\n" + tpl.Replace("$(EntryPoint)", ""); } decl += tpl; } decl = TemplateUtils.ReplaceTemplateVariable(decl, "BlankLine", ""); } else { string type = FormatType(member.Type); //if (type == null) type = features.objectKey; decl = acc + features.functionKey + " "; bool noRet = type == null || type.Equals("void", StringComparison.OrdinalIgnoreCase); type = (noRet && type != null) ? ASContext.Context.Features.voidKey : type; if (!noRet) { string qType = GetQualifiedType(type, ofClass); typesUsed.Add(qType); if (qType == type) { ClassModel rType = ASContext.Context.ResolveType(type, ofClass.InFile); if (!rType.IsVoid()) type = rType.Name; } } string action = (isProxy || isAS2Event) ? "" : GetSuperCall(member, typesUsed, ofClass); string template = TemplateUtils.GetTemplate("MethodOverride"); // fix parameters if needed if (member.Parameters != null) foreach (MemberModel para in member.Parameters) if (para.Type == "any") para.Type = "*"; template = TemplateUtils.ReplaceTemplateVariable(template, "Modifiers", acc); template = TemplateUtils.ReplaceTemplateVariable(template, "Name", member.Name); template = TemplateUtils.ReplaceTemplateVariable(template, "Arguments", TemplateUtils.ParametersString(member, true)); template = TemplateUtils.ReplaceTemplateVariable(template, "Type", type); template = TemplateUtils.ReplaceTemplateVariable(template, "Method", action); decl = template; } Sci.BeginUndoAction(); try { if (ASContext.Context.Settings.GenerateImports && typesUsed.Count > 0) { int offset = AddImportsByName(typesUsed, line); position += offset; startPos += offset; } Sci.SetSel(startPos, position + member.Name.Length); InsertCode(startPos, decl, Sci); } finally { Sci.EndUndoAction(); } }
public static void GenerateExtractMethod(ScintillaControl Sci, string NewName) { FileModel cFile; IASContext context = ASContext.Context; string selection = Sci.SelText; if (string.IsNullOrEmpty(selection)) { return; } if (selection.TrimStart().Length == 0) { return; } Sci.SetSel(Sci.SelectionStart + selection.Length - selection.TrimStart().Length, Sci.SelectionEnd); Sci.CurrentPos = Sci.SelectionEnd; 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; string template = TemplateUtils.GetTemplate("CallFunction"); template = TemplateUtils.ReplaceTemplateVariable(template, "Name", NewName); template = TemplateUtils.ReplaceTemplateVariable(template, "Arguments", ""); InsertCode(Sci.CurrentPos, template + ";", Sci); cFile = ASContext.Context.CurrentModel; ASFileParser parser = new ASFileParser(); parser.ParseSrc(cFile, Sci.Text); FoundDeclaration found = GetDeclarationAtLine(Sci, lineStart); if (found == null || found.member == null) { return; } lookupPosition = Sci.CurrentPos; AddLookupPosition(); MemberModel latest = TemplateUtils.GetTemplateBlockMember(Sci, TemplateUtils.GetBoundary("PrivateMethods")); if (latest == null) latest = GetLatestMemberForFunction(found.inClass, GetDefaultVisibility(found.inClass), found.member); if (latest == null) latest = found.member; int position = Sci.PositionFromLine(latest.LineTo + 1) - ((Sci.EOLMode == 0) ? 2 : 1); Sci.SetSel(position, position); FlagType flags = FlagType.Function; if ((found.member.Flags & FlagType.Static) > 0) { flags |= FlagType.Static; } MemberModel m = new MemberModel(NewName, context.Features.voidKey, flags, GetDefaultVisibility(found.inClass)); template = NewLine + TemplateUtils.GetTemplate("Function"); template = TemplateUtils.ToDeclarationWithModifiersString(m, template); template = TemplateUtils.ReplaceTemplateVariable(template, "Body", selText); template = TemplateUtils.ReplaceTemplateVariable(template, "BlankLine", NewLine); InsertCode(position, template, Sci); }
public PositionInfos(ScintillaControl sci, Int32 position, String argString) { // Variables String[] vars = argString.Split('¤'); this.ArgCurWord = vars[0]; this.ArgPackageName = vars[1]; this.ArgClassName = vars[2]; this.ArgClassType = vars[3]; this.ArgMemberName = vars[4]; this.ArgMemberType = vars[5]; // Selection Int32 ss = sci.SelectionStart; Int32 se = sci.SelectionEnd; if (se != ss) { this.SelectionStart = ss; this.SelectionEnd = se; this.HasSelection = true; if (sci.LineFromPosition(ss) != sci.LineFromPosition(se)) this.SelectionIsMultiline = true; else SelectedText = sci.SelText; } // Current this.CurrentPosition = position; this.CurrentCharCode = sci.CharAt(position); this.CurrentIsWhiteChar = (HelpTools.IsWhiteChar(this.CurrentCharCode)); this.CurrentIsDotChar = (this.CurrentCharCode == 46); this.CurrentIsActionScriptChar = HelpTools.IsActionScriptChar(this.CurrentCharCode); this.CurrentIsWordChar = HelpTools.IsWordChar((byte)this.CurrentCharCode); Int32 s = sci.StyleAt(position); this.CurrentIsInsideComment = (s == 1 || s == 2 || s == 3 || s == 17); // Next Int32 np = sci.PositionAfter(position); if (np != position) this.NextPosition = np; else this.CaretIsAtEndOfDocument = true; // Word this.CodePage = sci.CodePage; // (UTF-8|Big Endian|Little Endian : 65001) (8 Bits|UTF-7 : 0) if (this.CurrentIsInsideComment == false && this.SelectionIsMultiline == false) { Int32 wsp = sci.WordStartPosition(position, true); // Attention (WordEndPosition n'est pas estimé comme par defaut) Int32 wep = sci.PositionBefore(sci.WordEndPosition(position, true)); if (this.CodePage != 65001) { wsp = HelpTools.GetWordStartPositionByWordChar(sci, position); // Attention (WordEndPosition n'est pas estimé comme par defaut) wep = sci.PositionBefore(HelpTools.GetWordEndPositionByWordChar(sci, position)); } this.WordStartPosition = wsp; this.WordEndPosition = wep; if (this.CodePage == 65001) this.WordFromPosition = this.ArgCurWord; else this.WordFromPosition = HelpTools.GetText(sci, wsp, sci.PositionAfter(wep)); if (position > wep) this.CaretIsAfterLastLetter = true; } // Previous if (this.CurrentPosition > 0) { this.PreviousPosition = sci.PositionBefore(position); this.PreviousCharCode = sci.CharAt(this.PreviousPosition); this.PreviousIsWhiteChar = HelpTools.IsWhiteChar(this.PreviousCharCode); this.PreviousIsDotChar = (this.PreviousCharCode == 46); this.PreviousIsActionScriptChar = HelpTools.IsActionScriptChar(this.PreviousCharCode); } // Line this.CurrentLineIdx = sci.LineFromPosition(position); if (this.CurrentPosition > 0) this.PreviousLineIdx = sci.LineFromPosition(this.PreviousPosition); this.LineIdxMax = sci.LineCount - 1; this.LineStartPosition = HelpTools.LineStartPosition(sci, this.CurrentLineIdx); this.LineEndPosition = sci.LineEndPosition(this.CurrentLineIdx); this.NewLineMarker = LineEndDetector.GetNewLineMarker(sci.EOLMode); // Previous / Next if (this.WordStartPosition != -1) { this.PreviousNonWhiteCharPosition = HelpTools.PreviousNonWhiteCharPosition(sci, this.WordStartPosition); this.PreviousWordIsFunction = (sci.GetWordFromPosition(this.PreviousNonWhiteCharPosition) == "function"); this.NextNonWhiteCharPosition = HelpTools.NextNonWhiteCharPosition(sci, this.WordEndPosition); } // Function if (this.PreviousWordIsFunction) { Int32 nobp = HelpTools.NextCharPosition(sci, position, "("); Int32 ncbp = HelpTools.NextCharPosition(sci, position, ")"); Int32 nlbp = HelpTools.NextCharPosition(sci, position, "{"); if ((nobp < ncbp) && (ncbp < nlbp)) { this.NextOpenBracketPosition = nobp; this.NextCloseBracketPosition = ncbp; this.NextLeftBracePosition = nlbp; } // Arguments String args = HelpTools.GetText(sci, sci.PositionAfter(this.NextOpenBracketPosition), this.NextCloseBracketPosition).Trim(); if (args.Length > 0) { this.HasArguments = true; this.Arguments = HelpTools.ExtractArguments(sci, args); } } }
/// <summary> /// Checks if a given search match actually points to the given target source /// </summary> /// <returns>True if the SearchMatch does point to the target source.</returns> public static ASResult DeclarationLookupResult(ScintillaNet.ScintillaControl Sci, int position) { if (!ASContext.Context.IsFileValid || (Sci == null)) { return(null); } // get type at cursor position ASResult result = ASComplete.GetExpressionType(Sci, position); if (result.IsPackage) { return(result); } // open source and show declaration if (!result.IsNull()) { if (result.Member != null && (result.Member.Flags & FlagType.AutomaticVar) > 0) { return(null); } FileModel model = result.InFile ?? ((result.Member != null && result.Member.InFile != null) ? result.Member.InFile : null) ?? ((result.Type != null) ? result.Type.InFile : null); if (model == null || model.FileName == "") { return(null); } ClassModel inClass = result.InClass ?? result.Type; // for Back command int lookupLine = Sci.LineFromPosition(Sci.CurrentPos); int lookupCol = Sci.CurrentPos - Sci.PositionFromLine(lookupLine); ASContext.Panel.SetLastLookupPosition(ASContext.Context.CurrentFile, lookupLine, lookupCol); // open the file if (model != ASContext.Context.CurrentModel) { // cached files declarations have no line numbers if (model.CachedModel && model.Context != null) { ASFileParser.ParseFile(model); if (inClass != null && !inClass.IsVoid()) { inClass = model.GetClassByName(inClass.Name); if (result.Member != null) { result.Member = inClass.Members.Search(result.Member.Name, 0, 0); } } else { result.Member = model.Members.Search(result.Member.Name, 0, 0); } } if (model.FileName.Length > 0 && File.Exists(model.FileName)) { ASContext.MainForm.OpenEditableDocument(model.FileName, false); } else { ASComplete.OpenVirtualFile(model); result.InFile = ASContext.Context.CurrentModel; if (result.InFile == null) { return(null); } if (inClass != null) { inClass = result.InFile.GetClassByName(inClass.Name); if (result.Member != null) { result.Member = inClass.Members.Search(result.Member.Name, 0, 0); } } else if (result.Member != null) { result.Member = result.InFile.Members.Search(result.Member.Name, 0, 0); } } } if ((inClass == null || inClass.IsVoid()) && result.Member == null) { return(null); } Sci = ASContext.CurSciControl; if (Sci == null) { return(null); } int line = 0; string name = null; bool isClass = false; // member if (result.Member != null && result.Member.LineFrom > 0) { line = result.Member.LineFrom; name = result.Member.Name; } // class declaration else if (inClass.LineFrom > 0) { line = inClass.LineFrom; name = inClass.Name; isClass = true; // constructor foreach (MemberModel member in inClass.Members) { if ((member.Flags & FlagType.Constructor) > 0) { line = member.LineFrom; name = member.Name; isClass = false; break; } } } if (line > 0) // select { if (isClass) { ASComplete.LocateMember("(class|interface)", name, line); } else { ASComplete.LocateMember("(function|var|const|get|set|property|[,(])", name, line); } } return(result); } return(null); }
public override bool OnCompletionInsert(ScintillaControl sci, int position, string text, char trigger) { if (text == "Dictionary") { string insert = null; string line = sci.GetLine(sci.LineFromPosition(position)); Match m = Regex.Match(line, @"\svar\s+(?<varname>.+)\s*:\s*Dictionary\.<(?<indextype>.+)(?=(>\s*=))"); if (m.Success) { insert = String.Format(".<{0}>", m.Groups["indextype"].Value); } else { m = Regex.Match(line, @"\s*=\s*new"); if (m.Success) { ASResult result = ASComplete.GetExpressionType(sci, sci.PositionFromLine(sci.LineFromPosition(position)) + m.Index); if (result != null && !result.IsNull() && result.Member != null && result.Member.Type != null) { m = Regex.Match(result.Member.Type, @"(?<=<).+(?=>)"); if (m.Success) { insert = String.Format(".<{0}>", m.Value); } } } if (insert == null) { if (trigger == '.' || trigger == '(') return true; insert = ".<>"; sci.InsertText(position + text.Length, insert); sci.CurrentPos = position + text.Length + 2; sci.SetSel(sci.CurrentPos, sci.CurrentPos); ASComplete.HandleAllClassesCompletion(sci, "", false, true); return true; } } if (insert == null) return false; if (trigger == '.') { sci.InsertText(position + text.Length, insert.Substring(1)); sci.CurrentPos = position + text.Length; } else { sci.InsertText(position + text.Length, insert); sci.CurrentPos = position + text.Length + insert.Length; } sci.SetSel(sci.CurrentPos, sci.CurrentPos); return true; } return base.OnCompletionInsert(sci, position, text, trigger); }
public static void GoToLineEnd(ScintillaControl sci, Boolean insertNewLine) { sci.GotoPos(sci.LineEndPosition(sci.LineFromPosition(sci.CurrentPos))); if (insertNewLine) sci.NewLine(); }
private static void AssignStatementToVar(ClassModel inClass, ScintillaControl sci, MemberModel member) { int lineNum = sci.CurrentLine; string line = sci.GetLine(lineNum); StatementReturnType returnType = GetStatementReturnType(sci, inClass, line, sci.PositionFromLine(lineNum)); if (returnType == null) return; string type = null; string varname = null; ASResult resolve = returnType.resolve; string word = returnType.word; if (resolve != null && !resolve.IsNull()) { if (resolve.Member != null && resolve.Member.Type != null) { type = resolve.Member.Type; } else if (resolve.Type != null && resolve.Type.Name != null) { type = resolve.Type.QualifiedName; } if (resolve.Member != null && resolve.Member.Name != null) { varname = GuessVarName(resolve.Member.Name, type); } } if (!string.IsNullOrEmpty(word) && Char.IsDigit(word[0])) word = null; if (!string.IsNullOrEmpty(word) && (string.IsNullOrEmpty(type) || Regex.IsMatch(type, "(<[^]]+>)"))) word = null; if (!string.IsNullOrEmpty(type) && type.Equals("void", StringComparison.OrdinalIgnoreCase)) type = null; if (varname == null) varname = GuessVarName(word, type); if (varname != null && varname == word) varname = varname.Length == 1 ? varname + "1" : varname[0] + ""; string cleanType = null; if (type != null) cleanType = FormatType(GetShortType(type)); string template = TemplateUtils.GetTemplate("AssignVariable"); template = TemplateUtils.ReplaceTemplateVariable(template, "Name", varname); template = TemplateUtils.ReplaceTemplateVariable(template, "Type", cleanType); int indent = sci.GetLineIndentation(lineNum); int pos = sci.PositionFromLine(lineNum) + indent / sci.Indent; sci.CurrentPos = pos; sci.SetSel(pos, pos); InsertCode(pos, template, sci); if (type != null) { ClassModel inClassForImport = null; if (resolve.InClass != null) { inClassForImport = resolve.InClass; } else if (resolve.RelClass != null) { inClassForImport = resolve.RelClass; } else { inClassForImport = inClass; } List<string> l = new List<string>(); l.Add(GetQualifiedType(type, inClassForImport)); pos += AddImportsByName(l, sci.LineFromPosition(pos)); } }
private static void GenerateImplementation(ClassModel iType, ClassModel inClass, ScintillaControl sci, bool detached) { List<string> typesUsed = new List<string>(); StringBuilder sb = new StringBuilder(); string header = TemplateUtils.ReplaceTemplateVariable(TemplateUtils.GetTemplate("ImplementHeader"), "Class", iType.Type); header = TemplateUtils.ReplaceTemplateVariable(header, "BlankLine", detached ? BlankLine : null); sb.Append(header); sb.Append(NewLine); bool entry = true; ASResult result = new ASResult(); IASContext context = ASContext.Context; ContextFeatures features = context.Features; bool canGenerate = false; bool isHaxe = IsHaxe; FlagType flags = (FlagType.Function | FlagType.Getter | FlagType.Setter); if (isHaxe) flags |= FlagType.Variable; iType.ResolveExtends(); // resolve inheritance chain while (!iType.IsVoid() && iType.QualifiedName != "Object") { foreach (MemberModel method in iType.Members) { if ((method.Flags & flags) == 0 || method.Name == iType.Name) continue; // check if method exists ASComplete.FindMember(method.Name, inClass, result, method.Flags, 0); if (!result.IsNull()) continue; string decl; if ((method.Flags & FlagType.Getter) > 0) { if (isHaxe) { decl = TemplateUtils.ToDeclarationWithModifiersString(method, TemplateUtils.GetTemplate("Property")); string templateName = null; string metadata = null; if (method.Parameters[0].Name == "get") { if (method.Parameters[1].Name == "set") { templateName = "GetterSetter"; metadata = "@:isVar"; } else templateName = "Getter"; } else if (method.Parameters[1].Name == "set") { templateName = "Setter"; } decl = TemplateUtils.ReplaceTemplateVariable(decl, "MetaData", metadata); if (templateName != null) { var accessor = NewLine + TemplateUtils.ToDeclarationString(method, TemplateUtils.GetTemplate(templateName)); accessor = TemplateUtils.ReplaceTemplateVariable(accessor, "Modifiers", null); accessor = TemplateUtils.ReplaceTemplateVariable(accessor, "Member", method.Name); decl += accessor; } } else decl = TemplateUtils.ToDeclarationWithModifiersString(method, TemplateUtils.GetTemplate("Getter")); } else if ((method.Flags & FlagType.Setter) > 0) decl = TemplateUtils.ToDeclarationWithModifiersString(method, TemplateUtils.GetTemplate("Setter")); else if ((method.Flags & FlagType.Function) > 0) decl = TemplateUtils.ToDeclarationWithModifiersString(method, TemplateUtils.GetTemplate("Function")); else decl = NewLine + TemplateUtils.ToDeclarationWithModifiersString(method, TemplateUtils.GetTemplate("Variable")); decl = TemplateUtils.ReplaceTemplateVariable(decl, "Member", "_" + method.Name); decl = TemplateUtils.ReplaceTemplateVariable(decl, "Void", features.voidKey); decl = TemplateUtils.ReplaceTemplateVariable(decl, "Body", null); decl = TemplateUtils.ReplaceTemplateVariable(decl, "BlankLine", NewLine); if (!entry) { decl = TemplateUtils.ReplaceTemplateVariable(decl, "EntryPoint", null); } decl += NewLine; entry = false; sb.Append(decl); canGenerate = true; AddTypeOnce(typesUsed, GetQualifiedType(method.Type, iType)); if (method.Parameters != null && method.Parameters.Count > 0) foreach (MemberModel param in method.Parameters) AddTypeOnce(typesUsed, GetQualifiedType(param.Type, iType)); } // interface inheritance iType = iType.Extends; } if (!canGenerate) return; sci.BeginUndoAction(); try { int position = sci.CurrentPos; if (ASContext.Context.Settings.GenerateImports && typesUsed.Count > 0) { int offset = AddImportsByName(typesUsed, sci.LineFromPosition(position)); position += offset; sci.SetSel(position, position); } InsertCode(position, sb.ToString(), sci); } finally { sci.EndUndoAction(); } }
private static void ChangeDecl(ScintillaControl sci, MemberModel memberModel, List<FunctionParameter> functionParameters) { bool paramsDiffer = false; if (memberModel.Parameters != null) { // check that parameters have one and the same type if (memberModel.Parameters.Count == functionParameters.Count) { if (functionParameters.Count > 0) { List<MemberModel> parameters = memberModel.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 = memberModel.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.paramName, p.paramType, FlagType.ParameterVar, 0)); } } memberModel.Parameters = newParameters; int posStart = sci.PositionFromLine(memberModel.LineFrom); int posEnd = sci.LineEndPosition(memberModel.LineTo); sci.SetSel(posStart, posEnd); string selectedText = sci.SelText; Regex rStart = new Regex(@"\s{1}" + memberModel.Name + @"\s*\(([^\)]*)\)(\s*:\s*([^({{|\n|\r|\s|;)]+))?"); 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 = TemplateUtils.ToDeclarationString(memberModel, TemplateUtils.GetTemplate("MethodDeclaration")); InsertCode(sci.CurrentPos, "$(Boundary) " + decl, sci); // 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); } }
public static void GenerateDelegateMethods(ScintillaControl Sci, MemberModel member, Dictionary<MemberModel, ClassModel> selectedMembers, ClassModel classModel, ClassModel inClass) { Sci.BeginUndoAction(); try { string result = TemplateUtils.ReplaceTemplateVariable( TemplateUtils.GetTemplate("DelegateMethodsHeader"), "Class", classModel.Type); int position = -1; ClassModel type; List<string> importsList = new List<string>(); bool isStaticMember = false; if ((member.Flags & FlagType.Static) > 0) isStaticMember = true; inClass.ResolveExtends(); Dictionary<MemberModel, ClassModel>.KeyCollection selectedMemberKeys = selectedMembers.Keys; foreach (MemberModel m in selectedMemberKeys) { MemberModel mCopy = (MemberModel) m.Clone(); string methodTemplate = NewLine; bool overrideFound = false; ClassModel baseClassType = inClass; while (baseClassType != null && !baseClassType.IsVoid()) { MemberList inClassMembers = baseClassType.Members; foreach (MemberModel inClassMember in inClassMembers) { if ((inClassMember.Flags & FlagType.Function) > 0 && m.Name.Equals(inClassMember.Name)) { mCopy.Flags |= FlagType.Override; overrideFound = true; break; } } if (overrideFound) break; baseClassType = baseClassType.Extends; } if (isStaticMember && (m.Flags & FlagType.Static) == 0) mCopy.Flags |= FlagType.Static; if ((m.Flags & FlagType.Setter) > 0) { methodTemplate += TemplateUtils.GetTemplate("Setter"); methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Modifiers", (TemplateUtils.GetStaticExternOverride(m) + TemplateUtils.GetModifiers(m)).Trim()); methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Name", m.Name); methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "EntryPoint", ""); methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Type", m.Parameters[0].Type); methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Member", member.Name + "." + m.Name); methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Void", ASContext.Context.Features.voidKey ?? "void"); } else if ((m.Flags & FlagType.Getter) > 0) { methodTemplate += TemplateUtils.GetTemplate("Getter"); methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Modifiers", (TemplateUtils.GetStaticExternOverride(m) + TemplateUtils.GetModifiers(m)).Trim()); methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Name", m.Name); methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "EntryPoint", ""); methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Type", FormatType(m.Type)); methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Member", member.Name + "." + m.Name); } else { methodTemplate += TemplateUtils.GetTemplate("Function"); methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Body", "<<$(Return) >>$(Body)"); methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "EntryPoint", null); methodTemplate = TemplateUtils.ToDeclarationWithModifiersString(mCopy, methodTemplate); if (m.Type != null && m.Type.ToLower() != "void") methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Return", "return"); else methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Return", null); // check for varargs bool isVararg = false; if (m.Parameters != null && m.Parameters.Count > 0) { MemberModel mm = m.Parameters[m.Parameters.Count - 1]; if (mm.Name.StartsWithOrdinal("...")) isVararg = true; } string callMethodTemplate = TemplateUtils.GetTemplate("CallFunction"); if (!isVararg) { callMethodTemplate = TemplateUtils.ReplaceTemplateVariable(callMethodTemplate, "Name", member.Name + "." + m.Name); callMethodTemplate = TemplateUtils.ReplaceTemplateVariable(callMethodTemplate, "Arguments", TemplateUtils.CallParametersString(m)); callMethodTemplate += ";"; } else { List<MemberModel> pseudoParamsList = new List<MemberModel>(); pseudoParamsList.Add(new MemberModel("null", null, FlagType.ParameterVar, 0)); pseudoParamsList.Add(new MemberModel("[$(Subarguments)].concat($(Lastsubargument))", null, FlagType.ParameterVar, 0)); MemberModel pseudoParamsOwner = new MemberModel(); pseudoParamsOwner.Parameters = pseudoParamsList; callMethodTemplate = TemplateUtils.ReplaceTemplateVariable(callMethodTemplate, "Name", member.Name + "." + m.Name + ".apply"); callMethodTemplate = TemplateUtils.ReplaceTemplateVariable(callMethodTemplate, "Arguments", TemplateUtils.CallParametersString(pseudoParamsOwner)); callMethodTemplate += ";"; List<MemberModel> arrayParamsList = new List<MemberModel>(); for (int i = 0; i < m.Parameters.Count - 1; i++) { MemberModel param = m.Parameters[i]; arrayParamsList.Add(param); } pseudoParamsOwner.Parameters = arrayParamsList; callMethodTemplate = TemplateUtils.ReplaceTemplateVariable(callMethodTemplate, "Subarguments", TemplateUtils.CallParametersString(pseudoParamsOwner)); callMethodTemplate = TemplateUtils.ReplaceTemplateVariable(callMethodTemplate, "Lastsubargument", m.Parameters[m.Parameters.Count - 1].Name.TrimStart(new char[] { '.', ' '})); } methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Body", callMethodTemplate); } methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "BlankLine", NewLine); result += methodTemplate; if (m.Parameters != null) { for (int i = 0; i < m.Parameters.Count; i++) { MemberModel param = m.Parameters[i]; if (param.Type != null) { type = ASContext.Context.ResolveType(param.Type, selectedMembers[m].InFile); importsList.Add(type.QualifiedName); } } } if (position < 0) { MemberModel latest = GetLatestMemberForFunction(inClass, mCopy.Access, mCopy); if (latest == null) { position = Sci.WordStartPosition(Sci.CurrentPos, true); Sci.SetSel(position, Sci.WordEndPosition(position, true)); } else { position = Sci.PositionFromLine(latest.LineTo + 1) - ((Sci.EOLMode == 0) ? 2 : 1); Sci.SetSel(position, position); } } else { position = Sci.CurrentPos; } if (m.Type != null) { type = ASContext.Context.ResolveType(m.Type, selectedMembers[m].InFile); importsList.Add(type.QualifiedName); } } if (importsList.Count > 0 && position > -1) { int o = AddImportsByName(importsList, Sci.LineFromPosition(position)); position += o; Sci.SetSel(position, position); } InsertCode(position, result, Sci); } finally { Sci.EndUndoAction(); } }
private static void AddInterfaceDefJob(ClassModel inClass, ScintillaControl sci, MemberModel member, string interf) { ClassModel aType = ASContext.Context.ResolveType(interf, ASContext.Context.CurrentModel); if (aType.IsVoid()) return; FileModel fileModel = ASFileParser.ParseFile(ASContext.Context.CreateFileModel(aType.InFile.FileName)); foreach (ClassModel cm in fileModel.Classes) { if (cm.QualifiedName.Equals(aType.QualifiedName)) { aType = cm; break; } } string template = TemplateUtils.GetTemplate("IFunction"); if ((member.Flags & FlagType.Getter) > 0) { template = TemplateUtils.GetTemplate("IGetter"); } else if ((member.Flags & FlagType.Setter) > 0) { template = TemplateUtils.GetTemplate("ISetter"); } ASContext.MainForm.OpenEditableDocument(aType.InFile.FileName, true); sci = ASContext.CurSciControl; MemberModel latest = GetLatestMemberForFunction(aType, Visibility.Default, new MemberModel()); int position; if (latest == null) { position = GetBodyStart(aType.LineFrom, aType.LineTo, sci); } else { position = sci.PositionFromLine(latest.LineTo + 1) - ((sci.EOLMode == 0) ? 2 : 1); template = NewLine + template; } sci.SetSel(position, position); sci.CurrentPos = position; IASContext context = ASContext.Context; ContextFeatures features = context.Features; template = TemplateUtils.ToDeclarationString(member, template); template = TemplateUtils.ReplaceTemplateVariable(template, "BlankLine", NewLine); template = TemplateUtils.ReplaceTemplateVariable(template, "Void", features.voidKey); List<string> importsList = new List<string>(); string t; List<MemberModel> parms = member.Parameters; if (parms != null && parms.Count > 0) { for (int i = 0; i < parms.Count; i++) { if (parms[i].Type != null) { t = GetQualifiedType(parms[i].Type, inClass); importsList.Add(t); } } } if (member.Type != null) { t = GetQualifiedType(member.Type, inClass); importsList.Add(t); } if (importsList.Count > 0) { int o = AddImportsByName(importsList, sci.LineFromPosition(position)); position += o; } sci.SetSel(position, position); sci.CurrentPos = position; InsertCode(position, template, sci); }
public static void ContextualGenerator(ScintillaControl Sci, List<ICompletionListItem> options) { if (ASContext.Context is ASContext) (ASContext.Context as ASContext).UpdateCurrentFile(false); // update model if ((ASContext.Context.CurrentClass.Flags & (FlagType.Enum | FlagType.TypeDef)) > 0) return; lookupPosition = -1; int position = Sci.CurrentPos; int style = Sci.BaseStyleAt(position); if (style == 19) // on keyword return; bool isNotInterface = (ASContext.Context.CurrentClass.Flags & FlagType.Interface) == 0; int line = Sci.LineFromPosition(position); contextToken = Sci.GetWordFromPosition(position); contextMatch = null; FoundDeclaration found = GetDeclarationAtLine(Sci, line); string text = Sci.GetLine(line); bool suggestItemDeclaration = false; if (isNotInterface && ASComplete.IsLiteralStyle(style)) { ShowConvertToConst(found, options); return; } ASResult resolve = ASComplete.GetExpressionType(Sci, Sci.WordEndPosition(position, true)); contextResolved = resolve; // ignore automatic vars (MovieClip members) if (isNotInterface && resolve.Member != null && (((resolve.Member.Flags & FlagType.AutomaticVar) > 0) || (resolve.InClass != null && resolve.InClass.QualifiedName == "Object"))) { resolve.Member = null; resolve.Type = null; } if (isNotInterface && found.inClass != ClassModel.VoidClass && contextToken != null) { if (resolve.Member == null && resolve.Type != null && (resolve.Type.Flags & FlagType.Interface) > 0) // implement interface { contextParam = resolve.Type.Type; ShowImplementInterface(found, options); return; } if (resolve.Member != null && !ASContext.Context.CurrentClass.IsVoid() && (resolve.Member.Flags & FlagType.LocalVar) > 0) // promote to class var { contextMember = resolve.Member; ShowPromoteLocalAndAddParameter(found, options); return; } } if (contextToken != null && resolve.Member == null) // import declaration { if ((resolve.Type == null || resolve.Type.IsVoid() || !ASContext.Context.IsImported(resolve.Type, line)) && CheckAutoImport(found, options)) return; if (resolve.Type == null) { suggestItemDeclaration = ASComplete.IsTextStyle(Sci.BaseStyleAt(position - 1)); } } if (isNotInterface && found.member != null) { // private var -> property if ((found.member.Flags & FlagType.Variable) > 0 && (found.member.Flags & FlagType.LocalVar) == 0) { // maybe we just want to import the member's non-imported type Match m = Regex.Match(text, String.Format(patternVarDecl, found.member.Name, contextToken)); if (m.Success) { contextMatch = m; ClassModel type = ASContext.Context.ResolveType(contextToken, ASContext.Context.CurrentModel); if (type.IsVoid() && CheckAutoImport(found, options)) return; } ShowGetSetList(found, options); return; } // inside a function else if ((found.member.Flags & (FlagType.Function | FlagType.Getter | FlagType.Setter)) > 0 && resolve.Member == null && resolve.Type == null) { if (contextToken != null) { // "generate event handlers" suggestion string re = String.Format(patternEvent, contextToken); Match m = Regex.Match(text, re, RegexOptions.IgnoreCase); if (m.Success) { contextMatch = m; contextParam = CheckEventType(m.Groups["event"].Value); ShowEventList(found, options); return; } m = Regex.Match(text, String.Format(patternAS2Delegate, contextToken), RegexOptions.IgnoreCase); if (m.Success) { contextMatch = m; ShowDelegateList(found, options); return; } // suggest delegate if (ASContext.Context.Features.hasDelegates) { m = Regex.Match(text, @"([a-z0-9_.]+)\s*\+=\s*" + contextToken, RegexOptions.IgnoreCase); if (m.Success) { int offset = Sci.PositionFromLine(Sci.LineFromPosition(position)) + m.Groups[1].Index + m.Groups[1].Length; resolve = ASComplete.GetExpressionType(Sci, offset); if (resolve.Member != null) contextMember = ResolveDelegate(resolve.Member.Type, resolve.InFile); contextMatch = m; ShowDelegateList(found, options); return; } } } else { // insert a default handler name, then "generate event handlers" suggestion Match m = Regex.Match(text, String.Format(patternEvent, ""), RegexOptions.IgnoreCase); if (m.Success) { int regexIndex = m.Index + Sci.PositionFromLine(Sci.CurrentLine); GenerateDefaultHandlerName(Sci, position, regexIndex, m.Groups["event"].Value, true); resolve = ASComplete.GetExpressionType(Sci, Sci.CurrentPos); if (resolve.Member == null || (resolve.Member.Flags & FlagType.AutomaticVar) > 0) { contextMatch = m; contextParam = CheckEventType(m.Groups["event"].Value); ShowEventList(found, options); } return; } // insert default delegate name, then "generate delegate" suggestion if (ASContext.Context.Features.hasDelegates) { m = Regex.Match(text, @"([a-z0-9_.]+)\s*\+=\s*", RegexOptions.IgnoreCase); if (m.Success) { int offset = Sci.PositionFromLine(Sci.LineFromPosition(position)) + m.Groups[1].Index + m.Groups[1].Length; resolve = ASComplete.GetExpressionType(Sci, offset); if (resolve.Member != null) { contextMember = ResolveDelegate(resolve.Member.Type, resolve.InFile); string delegateName = resolve.Member.Name; if (delegateName.StartsWithOrdinal("on")) delegateName = delegateName.Substring(2); GenerateDefaultHandlerName(Sci, position, offset, delegateName, false); resolve = ASComplete.GetExpressionType(Sci, Sci.CurrentPos); if (resolve.Member == null || (resolve.Member.Flags & FlagType.AutomaticVar) > 0) { contextMatch = m; ShowDelegateList(found, options); } return; } } } } } // "Generate fields from parameters" suggestion if (found.member != null && (found.member.Flags & FlagType.Function) > 0 && found.member.Parameters != null && (found.member.Parameters.Count > 0) && resolve.Member != null && (resolve.Member.Flags & FlagType.ParameterVar) > 0) { contextMember = resolve.Member; ShowFieldFromParameter(found, options); return; } // "add to interface" suggestion if (resolve.Member != null && resolve.Member.Name == found.member.Name && line == found.member.LineFrom && ((found.member.Flags & FlagType.Function) > 0 || (found.member.Flags & FlagType.Getter) > 0 || (found.member.Flags & FlagType.Setter) > 0) && found.inClass != ClassModel.VoidClass && found.inClass.Implements != null && found.inClass.Implements.Count > 0) { string funcName = found.member.Name; FlagType flags = found.member.Flags & ~FlagType.Access; List<string> interfaces = new List<string>(); foreach (string interf in found.inClass.Implements) { bool skip = false; ClassModel cm = ASContext.Context.ResolveType(interf, ASContext.Context.CurrentModel); foreach (MemberModel m in cm.Members) { if (m.Name.Equals(funcName) && m.Flags.Equals(flags)) { skip = true; break; } } if (!skip) { interfaces.Add(interf); } } if (interfaces.Count > 0) { ShowAddInterfaceDefList(found, interfaces, options); return; } } // "assign var to statement" suggestion int curLine = Sci.CurrentLine; string ln = Sci.GetLine(curLine).TrimEnd(); if (ln.Length > 0 && ln.IndexOf('=') == -1 && ln.Length <= Sci.CurrentPos - Sci.PositionFromLine(curLine)) // cursor at end of line { ShowAssignStatementToVarList(found, options); return; } } // suggest generate constructor / toString if (isNotInterface && found.member == null && found.inClass != ClassModel.VoidClass && contextToken == null) { bool hasConstructor = false; bool hasToString = false; foreach (MemberModel m in ASContext.Context.CurrentClass.Members) { if (!hasConstructor && (m.Flags & FlagType.Constructor) > 0) hasConstructor = true; if (!hasToString && (m.Flags & FlagType.Function) > 0 && m.Name.Equals("toString")) hasToString = true; } if (!hasConstructor || !hasToString) { ShowConstructorAndToStringList(found, hasConstructor, hasToString, options); return; } } if (isNotInterface && resolve.Member != null && resolve.Type != null && resolve.Type.QualifiedName == ASContext.Context.Features.stringKey && found.inClass != ClassModel.VoidClass) { int lineStartPos = Sci.PositionFromLine(Sci.CurrentLine); string lineStart = text.Substring(0, Sci.CurrentPos - lineStartPos); Match m = Regex.Match(lineStart, String.Format(@"new\s+(?<event>\w+)\s*\(\s*\w+", lineStart)); if (m.Success) { Group g = m.Groups["event"]; ASResult eventResolve = ASComplete.GetExpressionType(Sci, lineStartPos + g.Index + g.Length); if (eventResolve != null && eventResolve.Type != null) { ClassModel aType = eventResolve.Type; aType.ResolveExtends(); while (!aType.IsVoid() && aType.QualifiedName != "Object") { if (aType.QualifiedName == "flash.events.Event") { contextParam = eventResolve.Type.QualifiedName; ShowEventMetatagList(found, options); return; } aType = aType.Extends; } } } } // suggest declaration if (contextToken != null) { if (suggestItemDeclaration) { Match m = Regex.Match(text, String.Format(patternClass, contextToken)); if (m.Success) { contextMatch = m; ShowNewClassList(found, options); } else if (!found.inClass.IsVoid()) { m = Regex.Match(text, String.Format(patternMethod, contextToken)); if (m.Success) { contextMatch = m; ShowNewMethodList(found, options); } else ShowNewVarList(found, options); } } else { if (resolve != null && resolve.InClass != null && resolve.InClass.InFile != null && resolve.Member != null && (resolve.Member.Flags & FlagType.Function) > 0 && File.Exists(resolve.InClass.InFile.FileName) && !resolve.InClass.InFile.FileName.StartsWithOrdinal(PathHelper.AppDir)) { Match m = Regex.Match(text, String.Format(patternMethodDecl, contextToken)); Match m2 = Regex.Match(text, String.Format(patternMethod, contextToken)); if (!m.Success && m2.Success) { contextMatch = m; ShowChangeMethodDeclList(found, options); } } else if (resolve != null && resolve.Type != null && resolve.Type.InFile != null && resolve.RelClass != null && File.Exists(resolve.Type.InFile.FileName) && !resolve.Type.InFile.FileName.StartsWithOrdinal(PathHelper.AppDir)) { Match m = Regex.Match(text, String.Format(patternClass, contextToken)); if (m.Success) { contextMatch = m; ShowChangeConstructorDeclList(found, options); } } } } // TODO: Empty line, show generators list? yep }
private static void GenerateFieldFromParameter(ScintillaControl sci, MemberModel member, ClassModel inClass, Visibility scope) { int funcBodyStart = GetBodyStart(member.LineFrom, member.LineTo, sci, false); int fbsLine = sci.LineFromPosition(funcBodyStart); int endPos = sci.LineEndPosition(member.LineTo); sci.SetSel(funcBodyStart, endPos); string body = sci.SelText; string trimmed = body.TrimStart(); Match m = reSuperCall.Match(trimmed); if (m.Success && m.Index == 0) { funcBodyStart = GetEndOfStatement(funcBodyStart + (body.Length - trimmed.Length), endPos, sci); } funcBodyStart = GetOrSetPointOfInsertion(funcBodyStart, endPos, fbsLine, sci); sci.SetSel(funcBodyStart, funcBodyStart); sci.CurrentPos = funcBodyStart; bool isVararg = false; string paramName = contextMember.Name; if (paramName.StartsWithOrdinal("...")) { paramName = paramName.TrimStart(new char[] { ' ', '.' }); isVararg = true; } string varName = paramName; string scopedVarName = varName; if ((scope & Visibility.Public) > 0) { if ((member.Flags & FlagType.Static) > 0) scopedVarName = inClass.Name + "." + varName; else scopedVarName = "this." + varName; } else { if (ASContext.CommonSettings.PrefixFields.Length > 0 && !paramName.StartsWithOrdinal(ASContext.CommonSettings.PrefixFields)) { scopedVarName = varName = ASContext.CommonSettings.PrefixFields + varName; } if (ASContext.CommonSettings.GenerateScope || ASContext.CommonSettings.PrefixFields == "") { if ((member.Flags & FlagType.Static) > 0) scopedVarName = inClass.Name + "." + varName; else scopedVarName = "this." + varName; } } string template = TemplateUtils.GetTemplate("FieldFromParameter"); template = TemplateUtils.ReplaceTemplateVariable(template, "Name", scopedVarName); template = TemplateUtils.ReplaceTemplateVariable(template, "Value", paramName); template += "\n$(Boundary)"; SnippetHelper.InsertSnippetText(sci, funcBodyStart, template); //TODO: We also need to check parent classes!!! MemberList classMembers = inClass.Members; foreach (MemberModel classMember in classMembers) if (classMember.Name.Equals(varName)) { ASContext.Panel.RestoreLastLookupPosition(); return; } MemberModel latest = GetLatestMemberForVariable(GeneratorJobType.Variable, inClass, GetDefaultVisibility(inClass), new MemberModel()); if (latest == null) return; int position = FindNewVarPosition(sci, inClass, latest); if (position <= 0) return; sci.SetSel(position, position); sci.CurrentPos = position; MemberModel mem = NewMember(varName, member, FlagType.Variable, scope); if (isVararg) mem.Type = "Array"; else mem.Type = contextMember.Type; GenerateVariable(mem, position, true); ASContext.Panel.RestoreLastLookupPosition(); }
/// <summary> /// Adds highlights to the correct sci control /// </summary> private void AddHighlights(ScintillaControl sci, List<SearchMatch> matches) { ITabbedDocument doc = DocumentManager.FindDocument(sci); Language language = MainForm.Instance.SciConfig.GetLanguage(sci.ConfigurationLanguage); foreach (SearchMatch match in matches) { Int32 start = sci.MBSafePosition(match.Index); Int32 end = start + sci.MBSafeTextLength(match.Value); Int32 line = sci.LineFromPosition(start); Int32 position = start; Int32 es = sci.EndStyled; Int32 mask = 1 << sci.StyleBits; // Define indics in both controls... doc.SplitSci1.SetIndicStyle(0, (Int32)ScintillaNet.Enums.IndicatorStyle.RoundBox); doc.SplitSci1.SetIndicFore(0, language.editorstyle.HighlightBackColor); doc.SplitSci2.SetIndicStyle(0, (Int32)ScintillaNet.Enums.IndicatorStyle.RoundBox); doc.SplitSci2.SetIndicFore(0, language.editorstyle.HighlightBackColor); sci.StartStyling(position, mask); sci.SetStyling(end - start, mask); sci.StartStyling(es, mask - 1); } }
/// <summary> /// Tries to get the start position of a code block, delimited by { and } /// </summary> /// <param name="lineFrom">The line inside the Scintilla document where the owner member of the body starts</param> /// <param name="lineTo">The line inside the Scintilla document where the owner member of the body ends</param> /// <param name="sci">The Scintilla control containing the document</param> /// <param name="needsPointOfInsertion">If true looks for the position to add new code, inserting new lines if needed</param> /// <returns>The position inside the Scintilla document, or -1 if not suitable position was found</returns> public static int GetBodyStart(int lineFrom, int lineTo, ScintillaControl sci, bool needsPointOfInsertion) { int posStart = sci.PositionFromLine(lineFrom); int posEnd = sci.LineEndPosition(lineTo); int funcBodyStart = -1; int genCount = 0; for (int i = posStart; i <= posEnd; i++) { char c = (char)sci.CharAt(i); if (c == '{') { int style = sci.BaseStyleAt(i); if (ASComplete.IsCommentStyle(style) || ASComplete.IsLiteralStyle(style) || genCount > 0) continue; funcBodyStart = i; break; } else if (c == '<') { int style = sci.BaseStyleAt(i); if (style == 10) genCount++; } else if (c == '>') { int style = sci.BaseStyleAt(i); if (style == 10) genCount--; } } if (funcBodyStart == -1) return -1; if (needsPointOfInsertion) { int ln = sci.LineFromPosition(funcBodyStart); funcBodyStart++; return GetOrSetPointOfInsertion(funcBodyStart, posEnd, ln, sci); } return funcBodyStart + 1; }
/// <summary> /// Handles the modified event /// </summary> public void OnScintillaControlModified(ScintillaControl sender, Int32 pos, Int32 modType, String text, Int32 length, Int32 lAdded, Int32 line, Int32 fLevelNow, Int32 fLevelPrev) { ITabbedDocument document = DocumentManager.FindDocument(sender); if (document != null && document.IsEditable) { this.OnDocumentModify(document); if (this.appSettings.ViewModifiedLines) { Int32 flags = sender.ModEventMask; sender.ModEventMask = flags & ~(Int32)ScintillaNet.Enums.ModificationFlags.ChangeMarker; Int32 modLine = sender.LineFromPosition(pos); sender.MarkerAdd(modLine, 2); for (Int32 i = 0; i <= lAdded; i++) { sender.MarkerAdd(modLine + i, 2); } sender.ModEventMask = flags; } } }
/// <summary> /// Looks for the best next position to insert new code, inserting new lines if needed /// </summary> /// <param name="startPos">The position inside the Scintilla document to start looking for the insertion position</param> /// <param name="endPos">The end position inside the Scintilla document</param> /// <param name="baseLine">The line inside the document to use as the base for the indentation level and detect if the desired point /// matches the end line</param> /// <param name="sci">The ScintillaControl where our document resides</param> /// <returns>The insertion point position</returns> private static int GetOrSetPointOfInsertion(int startPos, int endPos, int baseLine, ScintillaControl sci) { char[] characterClass = { ' ', '\r', '\n', '\t' }; int nCount = 0; int extraLine = 1; int initialLn = sci.LineFromPosition(startPos); int baseIndent = sci.GetLineIndentation(baseLine); bool found = false; while (startPos <= endPos) { char c = (char)sci.CharAt(startPos); if (Array.IndexOf(characterClass, c) == -1) { int endLn = sci.LineFromPosition(startPos); if (endLn == baseLine || endLn == initialLn) { sci.InsertText(startPos, sci.NewLineMarker); // Do we want to set the line indentation no matter what? {\r\t\t\t\r} -> {\r\t\r} // Better results in most cases, but maybe highly unwanted in others? sci.SetLineIndentation(++endLn, baseIndent + sci.Indent); startPos = sci.LineIndentPosition(endLn); } if (c == '}') { sci.InsertText(startPos, sci.NewLineMarker); sci.SetLineIndentation(endLn + 1, baseIndent); // In relation with previous comment... we'll reinden this one: {\r} -> {\r\t\r} if (sci.GetLineIndentation(endLn) <= baseIndent) { sci.SetLineIndentation(endLn, baseIndent + sci.Indent); startPos = sci.LineIndentPosition(endLn); } } found = true; break; } else if (sci.EOLMode == 1 && c == '\r' && (++nCount) > extraLine) { found = true; break; } else if (c == '\n' && (++nCount) > extraLine) { if (sci.EOLMode != 2) { startPos--; } found = true; break; } startPos++; } if (!found) startPos--; return startPos; }
/** * Refreshes the statusbar display and * updates the important edit buttons */ public void OnScintillaControlUpdateControl(ScintillaControl sci) { if (sci != this.CurSciControl) return; int column = sci.Column(sci.CurrentPos)+1; int line = sci.LineFromPosition(sci.CurrentPos)+1; string file = sci.Tag.ToString(); int eolMode = sci.EOLMode; string eol = (eolMode == 0) ? "CR+LF" : ((eolMode == 1) ? "CR" : "LF"); string txt = " Line: "+line+" | Column: "+column+" | EOL: ("+eol+") | "+file; // reduce the path to fit 128 chars max in the status bar while (txt.Length > 128 && re_pathDirectory.IsMatch(txt)) { txt = re_pathDirectory.Replace(txt, @"\...\", (int)1); } this.statusBarPanel.Text = txt; this.Text = this.CurDocument.Text+" - FlashDevelop"; this.CheckActiveEncodingButton(sci.Encoding.CodePage); this.CheckActiveLanguageButton(sci.ConfigurationLanguage); this.CheckActiveEOLButton(sci.EOLMode); this.UpdateButtonsEnabled(); // NotifyEvent ne = new NotifyEvent(EventType.UIRefresh); Global.Plugins.NotifyPlugins(this, ne); }
private static void GenerateVariableJob(GeneratorJobType job, ScintillaControl sci, MemberModel member, bool detach, ClassModel inClass) { int position = 0; MemberModel latest = null; bool isOtherClass = false; Visibility varVisi = job.Equals(GeneratorJobType.Variable) ? GetDefaultVisibility(inClass) : Visibility.Public; FlagType ft = 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)); 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) { if (contextOwnerResult.Member == null && contextOwnerResult.Type != null) { isStatic.Flags |= FlagType.Static; } } } else if (member != null && (member.Flags & FlagType.Static) > 0) { 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); } latest = GetLatestMemberForVariable(job, inClass, varVisi, 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 = null; 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, ft, varVisi); if (returnTypeStr != null) { newMember.Type = returnTypeStr; } else if (eventValue != null) { newMember.Type = eventValue; } GenerateVariable(newMember, position, detach); }
/// <summary> /// Applies the state object to a scintilla control /// </summary> private static void ApplyStateObject(ScintillaControl sci, StateObject so, Boolean restorePosition) { if (so.LineCount != sci.LineCount) return; sci.Refresh(); // Update the scintilla control state for (Int32 i = 0; i < so.FoldedLines.Count; i++) { Int32 foldedLine = so.FoldedLines[i]; sci.ToggleFold(foldedLine); } if (so.BookmarkedLines != null) { for (Int32 i = 0; i < so.BookmarkedLines.Count; i++) { Int32 bookmarkedLine = so.BookmarkedLines[i]; sci.MarkerAdd(bookmarkedLine, 0); } sci.Refresh(); // Update again } if (restorePosition) { sci.FirstVisibleLine = so.LineScroll; Int32 line = sci.LineFromPosition(so.Position); sci.SetSel(so.Position, so.Position); sci.EnsureVisible(line); } }
private static void GenerateFunctionJob(GeneratorJobType job, ScintillaControl sci, MemberModel member, bool detach, ClassModel inClass) { int position = 0; MemberModel latest = null; bool isOtherClass = false; Visibility funcVisi = 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)); 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) { if (contextOwnerResult.Member == null && contextOwnerResult.Type != null) { isStatic.Flags |= FlagType.Static; } } } else if (member != null && (member.Flags & FlagType.Static) > 0) { 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 = null; if ((isStatic.Flags & FlagType.Static) > 0) { blockTmpl = TemplateUtils.GetBoundary("StaticMethods"); } else if ((funcVisi & Visibility.Public) > 0) { blockTmpl = TemplateUtils.GetBoundary("PublicMethods"); } else { blockTmpl = TemplateUtils.GetBoundary("PrivateMethods"); } latest = TemplateUtils.GetTemplateBlockMember(sci, blockTmpl); if (latest == null || (!isOtherClass && member == null)) { latest = GetLatestMemberForFunction(inClass, funcVisi, 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> l = new List<string>(); foreach (FunctionParameter fp in functionParameters) { try { l.Add(fp.paramQualType); } catch (Exception) { } } int o = AddImportsByName(l, 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>(); for (int i = 0; i < functionParameters.Count; i++) { string name = functionParameters[i].paramName; string type = functionParameters[i].paramType; parameters.Add(new MemberModel(name, type, FlagType.ParameterVar, 0)); } MemberModel newMember = NewMember(contextToken, isStatic, FlagType.Function, funcVisi); newMember.Parameters = parameters; GenerateFunction(newMember, position, detach, inClass); }
/// <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 void nextLine(Object sender, EventArgs e) { int start = sci.SelectionStart < sci.SelectionEnd ? sci.SelectionStart : sci.SelectionEnd; int end = sci.SelectionStart > sci.SelectionEnd ? sci.SelectionStart : sci.SelectionEnd; int len = sci.LineFromPosition(end) - sci.LineFromPosition(start); sci.BeginUndoAction(); sci.SelectionStart = sci.PositionFromLine(sci.LineFromPosition(start)); sci.SelectionEnd = sci.PositionFromLine(sci.LineFromPosition(end) + 1); string selectStr = sci.SelText; sci.Clear(); sci.LineDown(); sci.InsertText(sci.PositionFromLine(sci.LineFromPosition(sci.CurrentPos)), selectStr); sci.SelectionStart = sci.PositionFromLine(start = sci.LineFromPosition(sci.CurrentPos)); sci.SelectionEnd = sci.LineEndPosition(start + len); sci.EndUndoAction(); }