public static List <IOperationProvider> CStyleLineCommentsConditionalSetup(string evaluatorType, bool wholeLine, bool trimWhiteSpace, string id) { string uncommentOperationId = "Uncomment (C style): (//) -> ()"; string reduceCommentsOperationId = "Reduce comment (C style): (////) -> (//)"; // temporary - one time test IOperationProvider uncomment = new Replacement("//", string.Empty, uncommentOperationId); IOperationProvider reduceComment = new Replacement("////", "//", reduceCommentsOperationId); ConditionalTokens tokens = new ConditionalTokens { IfTokens = new[] { "//#if" }, ElseTokens = new[] { "//#else" }, ElseIfTokens = new[] { "//#elseif" }, EndIfTokens = new[] { "//#endif" }, ActionableIfTokens = new[] { "////#if" }, ActionableElseIfTokens = new[] { "////#elseif" }, ActionableElseTokens = new[] { "////#else" }, ActionableOperations = new[] { uncommentOperationId, reduceCommentsOperationId } }; ConditionEvaluator evaluator = EvaluatorSelector.Select(evaluatorType); IOperationProvider conditional = new Conditional(tokens, wholeLine, trimWhiteSpace, evaluator, id); return(new List <IOperationProvider>() { conditional, reduceComment, uncomment }); }
public static List <IOperationProvider> RemLineCommentConditionalSetup(String evaluatorType, bool wholeLine, bool trimWhiteSpace, string id) { string uncommentOperationId = "Replacement (rem line): (rem) -> ()"; string reduceCommentOperationId = "Uncomment (rem line): (rem rem) -> (rem)"; IOperationProvider uncomment = new Replacement("rem", string.Empty, uncommentOperationId); IOperationProvider reduceComment = new Replacement("rem rem", "rem", reduceCommentOperationId); ConditionalTokens tokens = new ConditionalTokens { IfTokens = new[] { "rem #if" }, ElseTokens = new[] { "rem #else" }, ElseIfTokens = new[] { "rem #elseif" }, EndIfTokens = new[] { "rem #endif", "rem rem #endif" }, ActionableIfTokens = new[] { "rem rem #if" }, ActionableElseIfTokens = new[] { "rem rem #elseif" }, ActionableElseTokens = new[] { "rem rem #else" }, ActionableOperations = new[] { uncommentOperationId, reduceCommentOperationId } }; ConditionEvaluator evaluator = EvaluatorSelector.Select(evaluatorType); IOperationProvider conditional = new Conditional(tokens, wholeLine, trimWhiteSpace, evaluator, id); return(new List <IOperationProvider>() { conditional, reduceComment, uncomment }); }
public void OnRemoval() { //Have our observer clear out any active subscriptions we're still holding onto observer.EndAllObservations(); foreach (Replacement rep in lstReplacements) { //For each replacement effect this soul effect has, unregister it so it'll stop taking effect Replacement.Unregister(rep); } RemoveEffect(); bRemoved = true; if (ContSkillEngine.bDEBUGENGINE) { Debug.Log(sName + " has been removed"); } if (ShouldTriggerExpiration()) { ExpirationEffect(); if (ContSkillEngine.bDEBUGENGINE) { Debug.Log(sName + " has expired"); } } }
public override void OnEnter() { //First, increase the fatigue value of the character ContSkillEngine.Get().AddExec(new ExecChangeFatigue(null, chrOwner, nStunAmount, false)); //Then, add a replacement effect to cancel out any further stuns that we would take repStun = new Replacement() { //The list of replacement effects we'll include ourselves in lstExecReplacements = ExecStun.lstAllFullReplacements, //Note that the parameter type is the generic Executable // - should cast to the proper type if further checking is required shouldReplace = (Executable exec) => { Debug.Assert(typeof(ExecStun) == exec.GetType()); //replace only if the stunned character will be the character this effect is on return(((ExecStun)exec).chrTarget == this.chrOwner); }, //Just replace the executable with a completely new null executable execReplace = (Executable exec) => new ExecNull(exec.chrSource) }; //Register this replacement effect so that it will take effect Replacement.Register(repStun); //Let observers know to start paying attention to the fatigue value now // and to clear out any channeling time (if applicable) chrOwner.subFatigueChange.NotifyObs(); chrOwner.subChannelTimeChange.NotifyObs(); }
internal Replacement CreateReplacement(ReplacementVersionOne v1Replacement) { Replacement replacement = null; if (v1Replacement != null) { replacement = new Replacement(); if (v1Replacement.InsertedBytes != null) { replacement.InsertedContent = new ArtifactContent { Binary = v1Replacement.InsertedBytes }; } replacement.DeletedRegion = new Region { ByteLength = v1Replacement.DeletedLength, ByteOffset = v1Replacement.Offset }; } return(replacement); }
public void Evaluate() { grammar.FinishSetup(); using (new DebugLogTimer("Evaluate Frames")) { try { m_Culled = 0; m_RuleCount = 0; var initialState = new Replacement(); initialState.id = grammar.startShape; frames.Enqueue(new EvaluationStackFrame(initialState)); while (frames.Count > 0) { var frame = frames.Dequeue(); EvaluateFrame(frame); } } catch (TooManyShapesException e) { Debug.Log(e); } } using (new DebugLogTimer("Shape Sorting")) shapes.Sort((s1, s2) => s2.area.CompareTo(s1.area)); Debug.Log($"Shapes: {shapes.Count} Culled: {m_Culled}"); }
internal ReplacementVersionOne CreateReplacementVersionOne(Replacement v2Replacement, Encoding encoding) { ReplacementVersionOne replacement = null; if (v2Replacement != null) { replacement = new ReplacementVersionOne(); ArtifactContent insertedContent = v2Replacement.InsertedContent; if (insertedContent != null) { if (insertedContent.Binary != null) { replacement.InsertedBytes = insertedContent.Binary; } else if (insertedContent.Text != null) { if (encoding != null) { replacement.InsertedBytes = SarifUtilities.GetBase64String(insertedContent.Text, encoding); } else { // The encoding is null or not supported on the current platform throw new UnknownEncodingException(); } } } replacement.DeletedLength = v2Replacement.DeletedRegion.ByteLength; replacement.Offset = v2Replacement.DeletedRegion.ByteOffset; } return(replacement); }
public static List <IOperationProvider> GenerateConditionalSetup(string token, ConditionalKeywords keywords, ConditionalOperationOptions options) { string uncommentOperationId = $"Uncomment (line): {token} -> ()"; string reduceCommentOperationId = $"Reduce comment (line): ({token}{token}) -> ({token})"; IOperationProvider uncomment = new Replacement(token, string.Empty, uncommentOperationId); IOperationProvider reduceComment = new Replacement($"{token}{token}", token, reduceCommentOperationId); ConditionalTokens conditionalTokens = new ConditionalTokens { IfTokens = new[] { $"{token}{keywords.KeywordPrefix}{keywords.IfKeyword}" }, ElseTokens = new[] { $"{token}{keywords.KeywordPrefix}{keywords.ElseKeyword}" }, ElseIfTokens = new[] { $"{token}{keywords.KeywordPrefix}{keywords.ElseIfKeyword}" }, EndIfTokens = new[] { $"{token}{keywords.KeywordPrefix}{keywords.EndIfKeyword}", $"{token}{token}{keywords.KeywordPrefix}{keywords.EndIfKeyword}" }, ActionableIfTokens = new[] { $"{token}{token}{keywords.KeywordPrefix}{keywords.IfKeyword}" }, ActionableElseTokens = new[] { $"{token}{token}{keywords.KeywordPrefix}{keywords.ElseKeyword}" }, ActionableElseIfTokens = new[] { $"{token}{token}{keywords.KeywordPrefix}{keywords.ElseIfKeyword}" }, ActionableOperations = new[] { uncommentOperationId, reduceCommentOperationId } }; ConditionEvaluator evaluator = EvaluatorSelector.Select(options.EvaluatorType); IOperationProvider conditional = new Conditional(conditionalTokens, options.WholeLine, options.TrimWhitespace, evaluator, options.Id); return(new List <IOperationProvider>() { conditional, reduceComment, uncomment }); }
public void ToReplacementModel_RelativeUri_TextReplacement() { var mock = new Mock <IFileSystem>(); mock.Setup(fs => fs.FileExists(It.IsAny <string>())).Returns(false); mock.Setup(fs => fs.FileReadAllText(It.IsAny <string>())).Returns(CodeSample); var regionCache = new FileRegionsCache(fileSystem: mock.Object); Uri uri = new Uri(RelativeFilePath, UriKind.Relative); Replacement replacement = new Replacement { DeletedRegion = new Region { CharOffset = 196, CharLength = 14, }, InsertedContent = new ArtifactContent { Text = ReplacementText, }, }; ReplacementModel model = replacement.ToReplacementModel(regionCache, uri); model.Should().NotBeNull(); model.InsertedBytes.Should().BeNull(); model.InsertedString.Should().BeEquivalentTo(ReplacementText); model.Region.Should().NotBeNull(); model.Region.CharLength.Should().Be(14); model.Region.CharOffset.Should().Be(196); model.Region.IsBinaryRegion.Should().BeFalse(); model.Region.ByteOffset.Should().Be(-1); }
public void ToReplacementModel_RelativeUri_BinaryReplacement() { var mock = new Mock <IFileSystem>(); mock.Setup(fs => fs.FileExists(It.IsAny <string>())).Returns(false); mock.Setup(fs => fs.FileReadAllText(It.IsAny <string>())).Returns(CodeSample); var regionCache = new FileRegionsCache(fileSystem: mock.Object); Uri uri = new Uri(RelativeFilePath, UriKind.Relative); byte[] bytes = Encoding.UTF8.GetBytes(ReplacementText); Replacement replacement = new Replacement { DeletedRegion = new Region { ByteOffset = 210, }, InsertedContent = new ArtifactContent { Binary = Convert.ToBase64String(bytes), }, }; ReplacementModel model = replacement.ToReplacementModel(regionCache, uri); model.Should().NotBeNull(); model.InsertedString.Should().BeNull(); model.InsertedBytes.Should().BeEquivalentTo(bytes); model.Region.Should().NotBeNull(); model.Region.IsBinaryRegion.Should().BeTrue(); model.Region.CharOffset.Should().Be(-1); model.Region.ByteOffset.Should().Be(210); }
void ReplaceType(string name, int genericArgs, int offset, int length, bool memberType = false) { string type; if (genericArgs == 0) { type = session.ResolveIdentifierAsType(name, location); } else { type = session.ResolveIdentifierAsType(name + "`" + genericArgs, location); } if (string.IsNullOrEmpty(type)) { parentType = null; } else { if (memberType) { type = type.Substring(type.LastIndexOf('.') + 1); } else { type = "global::" + type; } parentType = type + GenerateGenericArgs(genericArgs); var replacement = new Replacement { Offset = offset, Length = length, NewText = type }; replacements.Add(replacement); } }
public static string validateReplacementsList(string replacementText, out List <Replacement> replacements) { try { replacements = new List <Replacement>(); if (replacementText == null || replacementText.Length == 0) { return(null); } string[] replacementsCommaSplitList = replacementText.Split(COMMA); string[] replacementArray = null; Replacement replacement = null; foreach (string replacementGroup in replacementsCommaSplitList) { if (replacementGroup.Length > 0) { replacementArray = replacementGroup.Split(COLON); replacement = new Replacement(replacementArray[0].Trim(), replacementArray[1].Trim()); replacements.Add(replacement); } } } catch (Exception e) { System.Console.WriteLine("ERROR: There was a problem with the replacement list. Please check your format and try again. "); replacements = null; return("ERROR: There was a problem with the replacement list. Please check your format and try again. " + e.StackTrace); } return(null); }
/// <summary> /// Initializes an empty evolutionary algorithm. /// </summary> public EvolutionaryAlgorithm() { operators = new List <Operator>(); matingSelectors = new List <Selector>(); environmentalSelectors = new List <Selector>(); replacement = new ChildrenOnlyReplacement(); }
public static bool Prefix(ref object arg0, ref object arg1) { arg0 = Replacement.ReplaceText(arg0.ToString()); arg1 = Replacement.ReplaceText(arg1.ToString()); return(true); }
public static ReplacementModel ToReplacementModel(this Replacement replacement, FileRegionsCache fileRegionsCache, Uri uri) { if (replacement == null) { return(null); } var model = new ReplacementModel { Region = uri.IsAbsoluteUri ? fileRegionsCache.PopulateTextRegionProperties(replacement.DeletedRegion, uri, populateSnippet: false) : replacement.DeletedRegion, }; if (model.Region.CharOffset >= 0) { // This is a text replacement. model.InsertedString = replacement.InsertedContent?.Text; } else { // This is a binary replacement, but don't try to convert the replacement // content to a string if there isn't any. if (replacement.InsertedContent?.Binary != null) { model.InsertedBytes = Convert.FromBase64String(replacement.InsertedContent.Binary); } } return(model); }
public async Task <IActionResult> Edit(int id, [Bind("ReplacementID,CatalogueID,ReplacingID")] Replacement replacement) { if (id != replacement.ReplacementID) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(replacement); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ReplacementExists(replacement.ReplacementID)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } ViewData["CatalogueID"] = new SelectList(_context.Catalogues.Where(a => a.Obsolete == true), "CatalogueID", "ProductName", replacement.CatalogueID); ViewData["ReplacingID"] = new SelectList(_context.Catalogues.Where(a => a.Obsolete == false), "CatalogueID", "ProductName", replacement.ReplacingID); return(View(replacement)); }
public void Create() { var replacement = new Replacement("old string", "new string"); Assert.AreEqual("old string", replacement.OldValue); Assert.AreEqual("new string", replacement.NewValue); }
internal string GetResolvedExpression() { if (replacements.Count == 0) { return(expression); } replacements.Sort(delegate(Replacement r1, Replacement r2) { return(r1.Offset.CompareTo(r2.Offset)); }); StringBuilder sb = new StringBuilder(); int i = 0; foreach (Replacement r in replacements) { sb.Append(expression, i, r.Offset - i); sb.Append(r.NewText); i = r.Offset + r.Length; } Replacement last = replacements [replacements.Count - 1]; sb.Append(expression, last.Offset + last.Length, expression.Length - (last.Offset + last.Length)); return(sb.ToString()); }
/// <summary> /// Replaces this value with the given value. /// </summary> /// <param name="other">The other value.</param> public void Replace(Value other) { Debug.Assert(other != null, "Invalid other node"); Debug.Assert(CanBeReplaced, "Cannot replace a non-replaceable value"); Debug.Assert(!IsReplaced, "Cannot replace a replaced value"); var target = other.Resolve(); Debug.Assert(target != this, "Invalid replacement cycle"); Replacement = target; // Propagate uses foreach (var use in allUses) { Replacement.AddUse(use.Target, use.Index); } // Notify nodes foreach (var use in allUses) { use.Target.OnReplacedNode(use.Index); } OnReplace(); }
private static void ParseReplacements(XElement root, ProjectImpl project, IProjectContext context) { List <Replacement> replacements = new List <Replacement>(); XElement node = root.Element("replacements"); if (node != null) { foreach (XElement item in node.Elements("replace")) { XAttribute tmp = null; Replacement v = new Replacement(); if ((tmp = item.Attribute("file")) != null) { v.FileName = tmp.Value; } if ((tmp = item.Attribute("with")) != null) { v.ReplacementFile = context.GetPhysicalFile(tmp.Value, project); } if ((tmp = item.Attribute("mode")) != null) { v.Mode = (FileNameMode)Enum.Parse(typeof(FileNameMode), tmp.Value, true); } replacements.Add(v); } } project.Replacements = replacements; }
/// <summary> /// Returns true if InputCollectionReplace instances are equal /// </summary> /// <param name="other">Instance of InputCollectionReplace to be compared</param> /// <returns>Boolean</returns> public bool Equals(InputCollectionReplace other) { if (other is null) { return(false); } if (ReferenceEquals(this, other)) { return(true); } return (( Input == other.Input || Input != null && other.Input != null && Input.SequenceEqual(other.Input) ) && ( Match == other.Match || Match != null && Match.Equals(other.Match) ) && ( Replacement == other.Replacement || Replacement != null && Replacement.Equals(other.Replacement) ) && ( IgnoreCase == other.IgnoreCase || IgnoreCase.Equals(other.IgnoreCase) )); }
internal CompiledRegexReplacement Compile(IResourceContext context) { return(new CompiledRegexReplacement( Pattern.GetStringValue(context), Replacement.GetStringValue(context), Replacement.GetValue(context))); }
public void TestMethod() { var r = new Replacement(); var currentDirectory = Directory.GetCurrentDirectory(); var backupDirectory = Path.Combine(currentDirectory, "Backup"); if (!Directory.Exists(backupDirectory)) { Directory.CreateDirectory(backupDirectory); } var sourceFilePath = Path.Combine(currentDirectory, "SourceFile.txt"); var targetFilePath = Path.Combine(currentDirectory, "TargetFile.txt"); var backupFilePath = Path.Combine(backupDirectory, "TargetFile.txt"); var sourceFile = File.ReadAllBytes(sourceFilePath); var targetFileBefore = File.ReadAllBytes(targetFilePath); r.Replace(sourceFilePath, backupFilePath, targetFilePath); var targetFileAfter = File.ReadAllBytes(targetFilePath); var backupFile = File.ReadAllBytes(backupFilePath); Assert.AreEqual(EqualByteArray(sourceFile, targetFileAfter), true); Assert.AreEqual(EqualByteArray(targetFileBefore, backupFile), true); }
private void ProcessSuggestions(DataGridViewCellEventArgs e) { var findValue = dgvSubstitutions.Rows[e.RowIndex].Cells[(int)Column.Find].Value; var replaceWithValue = dgvSubstitutions.Rows[e.RowIndex].Cells[(int)Column.ReplaceWith].Value; if (findValue != null && replaceWithValue != null) { var camelCaseReplacement = new Replacement ( find: findValue.ToString(), replaceWith: replaceWithValue.ToString() ); var substitutions = GetSubstitutions(); var caseSubstitutionsService = new CaseSubstitutionsService(camelCaseReplacement, substitutions); if (caseSubstitutionsService.Valid) { var suggestions = caseSubstitutionsService.Suggest(); if (suggestions.Any()) { AskAcceptSuggestions(suggestions); } } } }
public void RealizeEvolution() { Initialisation initialisation = new Initialisation(initialPopulationCount); // Initialisation - validated List <Path> population = initialisation.GenerateInitialPopulation(); for (int i = 0; i < population.Count; i++) { if (StaticOperations.ValidatePath(population[i]) == false) { throw new NotSupportedException(); } } // Evaluation Evaluation evaluation = new Evaluation(); evaluation.EvaluatePopulation(population); // Encoding List <Representation> representations = new List <Representation>(); Decoder decoder = new Decoder(); foreach (Path path in population) { Representation representation = decoder.EncodePath(path); representations.Add(representation); } // Evolution cycle for (int i = 0; i < evolutionCycles; i++) { // Selection Selection selection = new Selection(parentsCount, representations); List <Representation> parents = selection.SelectParents(); // Genetic operator - validated GeneticOperator geneticOperator = new GeneticOperator(descendantsCount, parents); List <Representation> descendants = geneticOperator.GenerateDescendants(); // Decoding List <Path> descendantPaths = new List <Path>(); foreach (Representation representation in descendants) { Path path = decoder.DecodeRepresentation(representation); if (StaticOperations.ValidatePath(path) == false) { throw new NotSupportedException(); } descendantPaths.Add(path); } // Evaluation evaluation.EvaluatePopulation(descendantPaths); for (int j = 0; j < descendants.Count; j++) { descendants[j].Fitness = descendantPaths[j].Fitness; } // Replacement Replacement replacement = new Replacement(parents, descendants, initialPopulationCount); representations = replacement.NextGeneration(); // Save to export file SaveTwoBestMembers(representations); } }
public static Grammar SimpleSquare() { var grammar = new Grammar(); grammar.name = "SimpleSquare"; grammar.backgroundColor = new HsvColor() { h = 20, s = 0.7f, v = 0.9f }; { var initRule = new Rule(); initRule.name = "init"; var s1 = new Replacement(); s1.id = "square"; s1.color = new HsvColor() { h = 100, s = 0.5f, v = 0.5f }; var s2 = new Replacement(); s2.id = "square"; s2.color = new HsvColor() { h = 200, s = 0.7f, v = 0.7f, a = 0.5f }; s2.transform *= Matrix4x4.Scale(new Vector3(0.5f, 0.5f, 1)); /* * var s3 = new ShapeDesc(); * s3.id = "square"; * s3.color = new HsvColor() { a = 1, h = 150, s = 0.2f, v = 0.1f }; * s3.transform *= Matrix4x4.Scale(new Vector3(0.2f, 0.2f, 0.2f)); */ initRule.replacements = new[] { s1, s2 }; grammar.startShape = "init"; grammar.AddRule(initRule); } { var squareRule = new Rule(); squareRule.name = "square"; var s1 = new Replacement(); s1.SetSquare(); s1.transform = Matrix4x4.Rotate(Quaternion.Euler(new Vector3(0, 0, 45))); s1.color = new HsvColor() { h = 45 }; squareRule.replacements = new[] { s1 }; grammar.AddRule(squareRule); } return(grammar); }
public void AddArgument(String Argument, String Value) { Replacement repl = new Replacement(); repl.Argument = Argument; repl.Value = Value; listArguments.Add(repl); }
//Call when initializing public static void Register(Replacement rep) { //Add ourselves to the list of all replacement effects, so we get our flag reset properly lstAllReplacements.Add(rep); //Then add ourselves to our Executable's list of replacement effects rep.lstExecReplacements.Add(rep); }
public Value Resolve() { if (IsReplaced) { Replacement = Replacement.Resolve(); } return(Replacement); }
public static bool Prefix(ref object[] arg) { arg = arg .Select(x => Replacement.ReplaceText(x.ToString())) .ToArray(); return(true); }
public Task(IEnumerable<TextFile> files, string regularExpression, string replacementExpression, object options = null) { _regexProcessor = new RegexProcessor(regularExpression); _replacement = new Replacement(replacementExpression); _files = files.ToArray(); _microTasks = new MicroTask[_files.Length]; _statisticsVector = new MicroTaskStatistics[_files.Length]; }
void ReplaceType (string name, int offset, int length) { string type = session.ResolveIdentifierAsType (name, location); if (!string.IsNullOrEmpty (type)) { type = "global::" + type; Replacement r = new Replacement () { Offset = offset, Length = length, NewText = type }; replacements.Add (r); } }
private bool Replace(Replacement callback) { TextDocument document = GetTextDocument(); string replacement = callback(document.Selection.Text); using (EditorExtensionsPackage.UndoContext((callback.Method.Name))) document.Selection.Insert(replacement, 0); return true; }
private bool Replace(Replacement callback) { TextDocument document = GetTextDocument(); string replacement = callback(document.Selection.Text); _dte.UndoContext.Open(callback.Method.Name); document.Selection.Insert(replacement, 0); _dte.UndoContext.Close(); return true; }
void ResolveType (string typeName, int genericArgCout, int offset, int length) { if (genericArgCout > 0) typeName += "<" + new string (',', genericArgCout - 1) + ">"; string type = session.ResolveIdentifierAsType (typeName, location); if (!string.IsNullOrEmpty (type)) { type = "global::" + type; Replacement r = new Replacement () { Offset = offset, Length=length, NewText = type }; replacements.Add (r); } }
private void SetupCommand(uint command, Replacement callback) { CommandID commandId = new CommandID(GuidList.guidEditorExtensionsCmdSet, (int)command); OleMenuCommand menuCommand = new OleMenuCommand((s, e) => Replace(callback), commandId); menuCommand.BeforeQueryStatus += (s, e) => { string selection = GetTextDocument().Selection.Text; menuCommand.Enabled = selection.Length > 0 && callback(selection) != selection; }; _mcs.AddCommand(menuCommand); }
private void SetupCommand(CommandId command, Replacement callback) { CommandID commandId = new CommandID(CommandGuids.guidEditorExtensionsCmdSet, (int)command); OleMenuCommand menuCommand = new OleMenuCommand((s, e) => Replace(callback), commandId); menuCommand.BeforeQueryStatus += (s, e) => { var document = GetTextDocument(); if (document == null) return; string selection = document.Selection.Text; menuCommand.Enabled = selection.Length > 0 && callback(selection) != selection; }; _mcs.AddCommand(menuCommand); }
public ElementPair Replace(Element original, Element replacement, out Replacement result) { Element newLhs; Element newRhs; result = Replacement.None; if (ReferenceEquals(Lhs, original)) { newLhs = replacement; result |= Replacement.Lhs; } else newLhs = Lhs.Replace(original, replacement); if (ReferenceEquals(Rhs, original)) { newRhs = replacement; result |= Replacement.Rhs; } else newRhs = Rhs.Replace(original, replacement); return new ElementPair(newLhs, newRhs); }
public ActionResult SetReplacement(String value, String replace) { using (DataContext dataContext = new DataContext()) { Replacement replacement = dataContext.Replacements.FirstOrDefault(q => q.Value == value); if (replacement == null) { replacement = new Replacement(); dataContext.Replacements.Add(replacement); } replacement.Value = value; replacement.ReplaceValue = replace; dataContext.SaveChanges(); return this.Json(new { success = true }); } }
void ReadReplacementsElement(XmlTextReader reader) { ReplacementCollection replacements = null; string scope = null; if (reader.HasAttributes) { reader.MoveToNextAttribute (); if (reader.Name == "scope") scope = reader.Value; } switch (scope) { case "global": replacements = GlobalReplacements; break; case "enum": replacements = EnumBackingTypeReplacements; break; default: throw new XmlException ("<replacements> must have a 'scope' " + "attribute with a value of either 'global' or 'enum'"); } while (reader.Read ()) { switch (reader.NodeType) { case XmlNodeType.EndElement: if (reader.Name == "replacements") return; break; case XmlNodeType.Element: switch (reader.Name) { case "regex": case "exact": case "prefix": var elementName = reader.Name; var replacement = new Replacement (); switch (reader.Name) { case "regex": replacement.Kind = ReplacementKind.Regex; break; case "exact": replacement.Kind = ReplacementKind.Exact; break; case "prefix": replacement.Kind = ReplacementKind.Prefix; break; } if (reader.HasAttributes) { while (reader.MoveToNextAttribute ()) { switch (reader.Name) { case "pattern": replacement.Pattern = reader.Value; break; case "replacement": replacement.Replace = reader.Value; break; default: throw new XmlException ("<" + elementName + ">: unexpected attribute '" + reader.Name + "'; expected 'pattern' or 'replacement'"); } } } if (!replacement.IsValid) throw new XmlException ("<" + elementName + "> must have 'pattern' and 'replacement' attributes"); replacements.Add (replacement); break; default: throw new XmlException ("<replacements>: unexpected element <" + reader.Name + ">; expected <regex>, <prefix>, or <exact>"); } break; } } }
public static string GetReplacementDirectory(Replacement directoryName) { return Enum.GetName(typeof(Replacement), directoryName); }
private void Replace(Replacement callback) { TextDocument document = GetTextDocument(); if (document == null) return; string replacement = callback(document.Selection.Text); using (WebEssentialsPackage.UndoContext((callback.Method.Name))) document.Selection.Insert(replacement, 0); }
public MicroTask(TextFile textFile, RegexProcessor regexProcessor, Replacement replacement) { _file = textFile; _regex = regexProcessor; _replacement = replacement; }
void ReplaceType (string name, int genericArgs, int offset, int length, bool memberType = false) { string type = null; if (genericArgs == 0) type = session.ResolveIdentifierAsType (name, location); else type = session.ResolveIdentifierAsType (name + "`" + genericArgs, location); if (string.IsNullOrEmpty (type)) { parentType = null; } else { if (memberType) { type = type.Substring (type.LastIndexOf ('.') + 1); } else { type = "global::" + type; } parentType = type + GenerateGenericArgs (genericArgs); var replacement = new Replacement { Offset = offset, Length = length, NewText = type }; replacements.Add (replacement); } }