Пример #1
0
        public void HandleEvent(Object sender, NotifyEvent e, HandlingPriority priority)
        {
            Project project;

            switch (e.Type)
            {
            case EventType.Command:
                DataEvent evt = (DataEvent)e;
                if (evt.Action == "ProjectManager.CreateNewFile")
                {
                    Hashtable table = evt.Data as Hashtable;
                    project = PluginBase.CurrentProject as Project;
                    if ((project.Language.StartsWithOrdinal("as") || project.Language == "haxe") && IsWizardTemplate(table["templatePath"] as String))
                    {
                        evt.Handled = true;
                        String className = table.ContainsKey("className") ? table["className"] as String : TextHelper.GetString("Wizard.Label.NewClass");
                        DisplayClassWizard(table["inDirectory"] as String, table["templatePath"] as String, className, table["constructorArgs"] as String, table["constructorArgTypes"] as List <String>);
                    }
                }
                break;

            case EventType.FileSwitch:
                if (PluginBase.MainForm.CurrentDocument.FileName == processOnSwitch)
                {
                    processOnSwitch = null;
                    if (lastFileOptions == null || lastFileOptions.interfaces == null)
                    {
                        return;
                    }
                    foreach (String cname in lastFileOptions.interfaces)
                    {
                        ASContext.Context.CurrentModel.Check();
                        ClassModel inClass = ASContext.Context.CurrentModel.GetPublicClass();
                        ASGenerator.SetJobContext(null, cname, null, null);
                        ASGenerator.GenerateJob(GeneratorJobType.ImplementInterface, null, inClass, null, null);
                    }
                    lastFileOptions = null;
                }
                break;

            case EventType.ProcessArgs:
                TextEvent te = e as TextEvent;
                project = PluginBase.CurrentProject as Project;
                if (lastFileFromTemplate != null && project != null && (project.Language.StartsWithOrdinal("as") || project.Language == "haxe"))
                {
                    te.Value = ProcessArgs(project, te.Value);
                }
                break;
            }
        }
Пример #2
0
                public string Haxe(string sourceText, ClassModel sourceModel, ClassModel interfaceToImplement)
                {
                    ASContext.Context.SetHaxeFeatures();
                    ASContext.Context.CurrentModel.Returns(new FileModel {
                        haXe = true
                    });
                    ASContext.Context.ResolveType(null, null).ReturnsForAnyArgs(interfaceToImplement);

                    sci.Text = sourceText;
                    sci.ConfigurationLanguage = "haxe";

                    ASGenerator.GenerateJob(GeneratorJobType.ImplementInterface, null, sourceModel, null, null);

                    return(sci.Text);
                }
Пример #3
0
                public string Common(Visibility scope, string sourceText, ClassModel sourceClassModel,
                                     int memberPos, int parameterPos)
                {
                    ASContext.Context.SetAs3Features();

                    var table = new Hashtable();

                    table["scope"] = scope;

                    sci.Text = sourceText;
                    sci.ConfigurationLanguage = "as3";

                    var inClass      = sourceClassModel;
                    var sourceMember = sourceClassModel.Members[memberPos];

                    ASGenerator.SetJobContext(null, null, sourceMember.Parameters[parameterPos], null);
                    ASGenerator.GenerateJob(GeneratorJobType.FieldFromPatameter, sourceMember, inClass, null, table);

                    return(sci.Text);
                }
Пример #4
0
        /**
         * Handles the incoming events
         */
        public void HandleEvent(Object sender, NotifyEvent e, HandlingPriority prority)
        {
            try
            {
                // ignore all events when leaving
                if (PluginBase.MainForm.ClosingEntirely)
                {
                    return;
                }
                // current active document
                ITabbedDocument doc = PluginBase.MainForm.CurrentDocument;

                // application start
                if (!started && e.Type == EventType.UIStarted)
                {
                    started = true;
                    PathExplorer.OnUIStarted();
                    // associate context to initial document
                    e = new NotifyEvent(EventType.SyntaxChange);
                    this.pluginUI.UpdateAfterTheme();
                }

                // editor ready?
                if (doc == null)
                {
                    return;
                }
                ScintillaNet.ScintillaControl sci = doc.IsEditable ? doc.SciControl : null;

                //
                //  Events always handled
                //
                bool      isValid;
                DataEvent de;
                switch (e.Type)
                {
                // caret position in editor
                case EventType.UIRefresh:
                    if (!doc.IsEditable)
                    {
                        return;
                    }
                    timerPosition.Enabled = false;
                    timerPosition.Enabled = true;
                    return;

                // key combinations
                case EventType.Keys:
                    Keys key = (e as KeyEvent).Value;
                    if (ModelsExplorer.HasFocus)
                    {
                        e.Handled = ModelsExplorer.Instance.OnShortcut(key);
                        return;
                    }
                    if (!doc.IsEditable)
                    {
                        return;
                    }
                    e.Handled = ASComplete.OnShortcut(key, sci);
                    return;

                // user-customized shortcuts
                case EventType.Shortcut:
                    de = e as DataEvent;
                    if (de.Action == "Completion.ShowHelp")
                    {
                        ASComplete.HelpKeys = (Keys)de.Data;
                        de.Handled          = true;
                    }
                    return;

                //
                // File management
                //
                case EventType.FileSave:
                    if (!doc.IsEditable)
                    {
                        return;
                    }
                    ASContext.Context.CheckModel(false);
                    // toolbar
                    isValid = ASContext.Context.IsFileValid;
                    if (isValid && !PluginBase.MainForm.SavingMultiple)
                    {
                        if (ASContext.Context.Settings.CheckSyntaxOnSave)
                        {
                            CheckSyntax(null, null);
                        }
                        ASContext.Context.RemoveClassCompilerCache();
                    }
                    return;

                case EventType.SyntaxDetect:
                    // detect Actionscript language version
                    if (!doc.IsEditable)
                    {
                        return;
                    }
                    if (doc.FileName.ToLower().EndsWith(".as"))
                    {
                        settingObject.LastASVersion = DetectActionscriptVersion(doc);
                        (e as TextEvent).Value      = settingObject.LastASVersion;
                        e.Handled = true;
                    }
                    break;

                case EventType.ApplySettings:
                case EventType.SyntaxChange:
                case EventType.FileSwitch:
                    if (!doc.IsEditable)
                    {
                        ASContext.SetCurrentFile(null, true);
                        ContextChanged();
                        return;
                    }
                    currentDoc = doc.FileName;
                    currentPos = sci.CurrentPos;
                    // check file
                    bool ignoreFile = !doc.IsEditable;
                    ASContext.SetCurrentFile(doc, ignoreFile);
                    // UI
                    ContextChanged();
                    return;

                case EventType.Completion:
                    if (ASContext.Context.IsFileValid)
                    {
                        e.Handled = true;
                    }
                    return;

                // some commands work all the time
                case EventType.Command:
                    de = e as DataEvent;
                    string command = de.Action ?? "";

                    if (command.StartsWith("ASCompletion."))
                    {
                        string cmdData = (de.Data is string) ? (string)de.Data : null;

                        // add a custom classpath
                        if (command == "ASCompletion.ClassPath")
                        {
                            Hashtable info = de.Data as Hashtable;
                            if (info != null)
                            {
                                ContextSetupInfos setup = new ContextSetupInfos();
                                setup.Platform    = (string)info["platform"];
                                setup.Lang        = (string)info["lang"];
                                setup.Version     = (string)info["version"];
                                setup.TargetBuild = (string)info["targetBuild"];
                                setup.Classpath   = (string[])info["classpath"];
                                setup.HiddenPaths = (string[])info["hidden"];
                                ASContext.SetLanguageClassPath(setup);
                                if (setup.AdditionalPaths != null)     // report custom classpath
                                {
                                    info["additional"] = setup.AdditionalPaths.ToArray();
                                }
                            }
                            e.Handled = true;
                        }

                        // send a UserClasspath
                        else if (command == "ASCompletion.GetUserClasspath")
                        {
                            Hashtable info = de.Data as Hashtable;
                            if (info != null && info.ContainsKey("language"))
                            {
                                IASContext context = ASContext.GetLanguageContext(info["language"] as string);
                                if (context != null && context.Settings != null &&
                                    context.Settings.UserClasspath != null)
                                {
                                    info["cp"] = new List <string>(context.Settings.UserClasspath);
                                }
                            }
                            e.Handled = true;
                        }
                        // update a UserClasspath
                        else if (command == "ASCompletion.SetUserClasspath")
                        {
                            Hashtable info = de.Data as Hashtable;
                            if (info != null && info.ContainsKey("language") && info.ContainsKey("cp"))
                            {
                                IASContext    context = ASContext.GetLanguageContext(info["language"] as string);
                                List <string> cp      = info["cp"] as List <string>;
                                if (cp != null && context != null && context.Settings != null)
                                {
                                    string[] pathes = new string[cp.Count];
                                    cp.CopyTo(pathes);
                                    context.Settings.UserClasspath = pathes;
                                }
                            }
                            e.Handled = true;
                        }
                        // send the language's default compiler path
                        else if (command == "ASCompletion.GetCompilerPath")
                        {
                            Hashtable info = de.Data as Hashtable;
                            if (info != null && info.ContainsKey("language"))
                            {
                                IASContext context = ASContext.GetLanguageContext(info["language"] as string);
                                if (context != null)
                                {
                                    info["compiler"] = context.GetCompilerPath();
                                }
                            }
                            e.Handled = true;
                        }

                        // show a language's compiler settings
                        else if (command == "ASCompletion.ShowSettings")
                        {
                            e.Handled = true;
                            IASContext context = ASContext.GetLanguageContext(cmdData);
                            if (context == null)
                            {
                                return;
                            }
                            string filter = "SDK";
                            string name   = "";
                            switch (cmdData.ToUpper())
                            {
                            case "AS2": name = "AS2Context"; break;

                            case "AS3": name = "AS3Context"; break;

                            default:
                                name = cmdData.Substring(0, 1).ToUpper() + cmdData.Substring(1) + "Context";
                                break;
                            }
                            PluginBase.MainForm.ShowSettingsDialog(name, filter);
                        }

                        // Open types explorer dialog
                        else if (command == "ASCompletion.TypesExplorer")
                        {
                            TypesExplorer(null, null);
                        }

                        // call the Flash IDE
                        else if (command == "ASCompletion.CallFlashIDE")
                        {
                            if (flashErrorsWatcher == null)
                            {
                                flashErrorsWatcher = new FlashErrorsWatcher();
                            }
                            e.Handled = Commands.CallFlashIDE.Run(settingObject.PathToFlashIDE, cmdData);
                        }

                        // create Flash 8+ trust file
                        else if (command == "ASCompletion.CreateTrustFile")
                        {
                            if (cmdData != null)
                            {
                                string[] args = cmdData.Split(';');
                                if (args.Length == 2)
                                {
                                    e.Handled = Commands.CreateTrustFile.Run(args[0], args[1]);
                                }
                            }
                        }
                        else if (command == "ASCompletion.GetClassPath")
                        {
                            if (cmdData != null)
                            {
                                string[] args = cmdData.Split(';');
                                if (args.Length == 1)
                                {
                                    FileModel  model  = ASContext.Context.GetFileModel(args[0]);
                                    ClassModel aClass = model.GetPublicClass();
                                    if (!aClass.IsVoid())
                                    {
                                        Clipboard.SetText(aClass.QualifiedName);
                                        e.Handled = true;
                                    }
                                }
                            }
                        }
                        else if (command == "ProjectManager.FileActions.DisableWatchers")
                        {
                            foreach (PathModel cp in ASContext.Context.Classpath)
                            {
                                cp.DisableWatcher();
                            }
                        }
                        else if (command == "ProjectManager.FileActions.EnableWatchers")
                        {
                            // classpaths could be invalid now - remove those, BuildClassPath() is too expensive
                            ASContext.Context.Classpath.RemoveAll(cp => !Directory.Exists(cp.Path));

                            foreach (PathModel cp in ASContext.Context.Classpath)
                            {
                                cp.EnableWatcher();
                            }
                        }

                        // Return requested language SDK list
                        else if (command == "ASCompletion.InstalledSDKs")
                        {
                            Hashtable info = de.Data as Hashtable;
                            if (info != null && info.ContainsKey("language"))
                            {
                                IASContext context = ASContext.GetLanguageContext(info["language"] as string);
                                if (context != null)
                                {
                                    info["sdks"] = context.Settings.InstalledSDKs;
                                }
                            }
                            e.Handled = true;
                        }
                    }

                    // Create a fake document from a FileModel
                    else if (command == "ProjectManager.OpenVirtualFile")
                    {
                        string cmdData = de.Data as string;
                        if (reVirtualFile.IsMatch(cmdData))
                        {
                            string[] path     = Regex.Split(cmdData, "::");
                            string   fileName = path[0] + Path.DirectorySeparatorChar
                                                + path[1].Replace('.', Path.DirectorySeparatorChar).Replace("::", Path.DirectorySeparatorChar.ToString());
                            FileModel found = ModelsExplorer.Instance.OpenFile(fileName);
                            if (found != null)
                            {
                                e.Handled = true;
                            }
                        }
                    }
                    else if (command == "ProjectManager.UserRefreshTree")
                    {
                        ASContext.Context.UserRefreshRequest();
                    }
                    break;
                }

                //
                // Actionscript context specific
                //
                if (ASContext.Context.IsFileValid)
                {
                    switch (e.Type)
                    {
                    case EventType.ProcessArgs:
                        TextEvent te = (TextEvent)e;
                        if (reArgs.IsMatch(te.Value))
                        {
                            // resolve current element
                            Hashtable details = ASComplete.ResolveElement(sci, null);
                            te.Value = ArgumentsProcessor.Process(te.Value, details);

                            if (te.Value.IndexOf("$") >= 0 && reCostlyArgs.IsMatch(te.Value))
                            {
                                ASResult result = ASComplete.CurrentResolvedContext.Result ?? new ASResult();
                                details = new Hashtable();
                                // Get closest list (Array or Vector)
                                string closestListName = "", closestListItemType = "";
                                ASComplete.FindClosestList(ASContext.Context, result.Context, sci.CurrentLine, ref closestListName, ref closestListItemType);
                                details.Add("TypClosestListName", closestListName);
                                details.Add("TypClosestListItemType", closestListItemType);
                                // get free iterator index
                                string iterator = ASComplete.FindFreeIterator(ASContext.Context, ASContext.Context.CurrentClass, result.Context);
                                details.Add("ItmUniqueVar", iterator);
                                te.Value = ArgumentsProcessor.Process(te.Value, details);
                            }
                        }
                        break;

                    // menu commands
                    case EventType.Command:
                        string command = (e as DataEvent).Action ?? "";
                        if (command.StartsWith("ASCompletion."))
                        {
                            string cmdData = (e as DataEvent).Data as string;
                            // run MTASC
                            if (command == "ASCompletion.CustomBuild")
                            {
                                if (cmdData != null)
                                {
                                    ASContext.Context.RunCMD(cmdData);
                                }
                                else
                                {
                                    ASContext.Context.RunCMD("");
                                }
                                e.Handled = true;
                            }

                            // build the SWF using MTASC
                            else if (command == "ASCompletion.QuickBuild")
                            {
                                ASContext.Context.BuildCMD(false);
                                e.Handled = true;
                            }

                            // resolve element under cusor and open declaration
                            else if (command == "ASCompletion.GotoDeclaration")
                            {
                                ASComplete.DeclarationLookup(sci);
                                e.Handled = true;
                            }

                            // resolve element under cursor and send a CustomData event
                            else if (command == "ASCompletion.ResolveElement")
                            {
                                ASComplete.ResolveElement(sci, cmdData);
                                e.Handled = true;
                            }
                            else if (command == "ASCompletion.MakeIntrinsic")
                            {
                                ASContext.Context.MakeIntrinsic(cmdData);
                                e.Handled = true;
                            }

                            // alternative to default shortcuts
                            else if (command == "ASCompletion.CtrlSpace")
                            {
                                ASComplete.OnShortcut(Keys.Control | Keys.Space, ASContext.CurSciControl);
                                e.Handled = true;
                            }
                            else if (command == "ASCompletion.CtrlShiftSpace")
                            {
                                ASComplete.OnShortcut(Keys.Control | Keys.Shift | Keys.Space, ASContext.CurSciControl);
                                e.Handled = true;
                            }
                            else if (command == "ASCompletion.CtrlAltSpace")
                            {
                                ASComplete.OnShortcut(Keys.Control | Keys.Alt | Keys.Space, ASContext.CurSciControl);
                                e.Handled = true;
                            }
                            else if (command == "ASCompletion.ContextualGenerator")
                            {
                                if (ASContext.HasContext && ASContext.Context.IsFileValid)
                                {
                                    ASGenerator.ContextualGenerator(ASContext.CurSciControl);
                                }
                            }
                        }
                        return;

                    case EventType.ProcessEnd:
                        string procResult = (e as TextEvent).Value;
                        ASContext.Context.OnProcessEnd(procResult);
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorManager.ShowError(ex);
            }
        }
        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();
            }
        }
Пример #6
0
 public bool HandleOverride(string fileName)
 {
     SetSrc(sci, ReadAllText(fileName));
     SetCurrentFile(fileName);
     return(ASGenerator.HandleGeneratorCompletion(sci, false, ASContext.Context.Features.overrideKey));
 }
        public void Execute()
        {
            ScintillaControl Sci = PluginBase.MainForm.CurrentDocument.SciControl;

            ASGenerator.GenerateDelegateMethods(Sci, result.Member, selectedMembers, result.Type, result.InClass);
        }
Пример #8
0
        private void FindFinished(FRResults results)
        {
            UserInterfaceManager.ProgressDialog.Show();
            UserInterfaceManager.ProgressDialog.SetTitle(TextHelper.GetString("Info.UpdatingReferences"));
            MessageBar.Locked = true;
            var    currentTarget = targets[currentTargetIndex];
            string targetName    = Path.GetFileNameWithoutExtension(currentTarget.OldFilePath);
            string oldType       = (currentTarget.OldFileModel.Package + "." + targetName).Trim('.');
            string newType       = (currentTarget.NewPackage + "." + targetName).Trim('.');

            foreach (KeyValuePair <string, List <SearchMatch> > entry in results)
            {
                List <SearchMatch> matches = entry.Value;
                if (matches.Count == 0 || entry.Key == currentTarget.OldFilePath ||
                    entry.Key == currentTarget.NewFilePath)
                {
                    continue;
                }
                string file = entry.Key;
                UserInterfaceManager.ProgressDialog.UpdateStatusMessage(TextHelper.GetString("Info.Updating") + " \"" + file + "\"");
                ITabbedDocument  doc;
                ScintillaControl sci;
                var actualMatches = new List <SearchMatch>();
                foreach (SearchMatch match in entry.Value)
                {
                    // we have to open/reopen the entry's file
                    // there are issues with evaluating the declaration targets with non-open, non-current files
                    // we have to do it each time as the process of checking the declaration source can change the currently open file!
                    sci = AssociatedDocumentHelper.LoadDocument(file).SciControl;
                    // if the search result does point to the member source, store it
                    if (RefactoringHelper.DoesMatchPointToTarget(sci, match, currentTargetResult, this.AssociatedDocumentHelper))
                    {
                        actualMatches.Add(match);
                    }
                }
                if (actualMatches.Count == 0)
                {
                    continue;
                }
                int currLine = -1;
                doc = AssociatedDocumentHelper.LoadDocument(file);
                sci = doc.SciControl;
                string directory = Path.GetDirectoryName(file);
                // Let's check if we need to add the import. Check the considerations at the start of the file
                // directory != currentTarget.OwnerPath -> renamed owner directory, so both files in the same place
                bool needsImport = directory != Path.GetDirectoryName(currentTarget.NewFilePath) &&
                                   directory != currentTarget.OwnerPath &&
                                   ASContext.Context.CurrentModel.Imports.Search(targetName,
                                                                                 FlagType.Class & FlagType.Function &
                                                                                 FlagType.Namespace, 0) == null;

                // Replace matches
                int typeDiff        = sci.MBSafeTextLength(oldType) - sci.MBSafeTextLength(targetName);
                int newTypeDiff     = sci.MBSafeTextLength(newType) - sci.MBSafeTextLength(oldType);
                int accumulatedDiff = 0;
                int j = 0;
                for (int i = 0, count = actualMatches.Count; i < count; i++)
                {
                    var sm = actualMatches[j];
                    if (currLine == -1)
                    {
                        currLine = sm.Line - 1;
                    }
                    if (sm.LineText.Contains(oldType))
                    {
                        sm.Index -= typeDiff - accumulatedDiff;
                        sm.Value  = oldType;
                        RefactoringHelper.SelectMatch(sci, sm);
                        sm.Column -= typeDiff;
                        sci.ReplaceSel(newType);
                        sm.LineEnd  = sci.SelectionEnd;
                        sm.LineText = sm.LineText.Replace(oldType, newType);
                        sm.Length   = oldType.Length;
                        sm.Value    = newType;
                        if (needsImport)
                        {
                            sm.Line++;
                        }
                        accumulatedDiff += newTypeDiff;
                        j++;
                    }
                    else
                    {
                        actualMatches.RemoveAt(j);
                    }
                }
                if (needsImport)
                {
                    sci.GotoLine(currLine);
                    ASGenerator.InsertImport(new MemberModel(targetName, newType, FlagType.Import, 0), false);
                    int newLine = sci.LineFromPosition(sci.Text.IndexOfOrdinal(newType));
                    var sm      = new SearchMatch();
                    sm.Line     = newLine + 1;
                    sm.LineText = sci.GetLine(newLine);
                    sm.Column   = 0;
                    sm.Length   = sci.MBSafeTextLength(sm.LineText);
                    sm.Value    = sm.LineText;

                    actualMatches.Insert(0, sm);
                }
                if (actualMatches.Count == 0)
                {
                    continue;
                }
                if (!Results.ContainsKey(file))
                {
                    Results[file] = new List <SearchMatch>();
                }
                Results[file].AddRange(actualMatches);
                //Do we want to open modified files?
                //if (sci.IsModify) AssociatedDocumentHelper.MarkDocumentToKeep(file);
                doc.Save();
            }

            currentTargetIndex++;

            UserInterfaceManager.ProgressDialog.Hide();
            MessageBar.Locked = false;
            UpdateReferencesNextTarget();
        }
        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();
            }
        }