Ejemplo n.º 1
0
 public void Manage_Newlines()
 {
     var dict = new StringDictionary { { "temp", "temporary" } };
     var replacer = new Replacer(dict);
     Assert.That(replacer.Replace("$temp$\r\nword"),
         Is.EqualTo("temporary\r\nword"));
 }
Ejemplo n.º 2
0
 public void Test_Two_Words()
 {
     var dict = new StringDictionary
                {
                    { "greeting", "Watch out!" },
                    { "name", "John Doe" }
                };
     var replacer = new Replacer(dict);
     Assert.That(replacer.Replace("$greeting$ here comes $name$"),
                 Is.EqualTo("Watch out! here comes John Doe"));
 }
Ejemplo n.º 3
0
        public void Replace_WhenSearchTextIsRegularExpression_ReplacesTextInOne()
        {
            Replacer replacer = new Replacer();

            replacer.Dir              = _tempDir;
            replacer.FileMask         = "*.*";
            replacer.FindText         = @"\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b";     //email pattern
            replacer.ReplaceText      = "Email was here..";
            replacer.FindTextHasRegEx = true;

            var resultItems = replacer.Replace().ResultItems;

            if (resultItems == null || resultItems.Count == 0)
            {
                Assert.Fail("Can't find test files");
            }

            Assert.AreEqual(1, resultItems.Count);
            Assert.AreEqual("test2.txt", resultItems[0].FileName);
            Assert.AreEqual(1, resultItems[0].NumMatches);
        }
Ejemplo n.º 4
0
        public void Replace_WhenFileIsReadonly_CanNotRepacesText()
        {
            Replacer replacer = new Replacer();

            replacer.Dir         = _tempDir;
            replacer.FileMask    = "*.*";
            replacer.FindText    = "readonly";
            replacer.ReplaceText = "I can replace";

            var resultItems = replacer.Replace().ResultItems.Where(r => !r.IsSuccess).ToList();

            if (resultItems == null || resultItems.Count == 0)
            {
                Assert.Fail("Can't find test files");
            }

            Assert.AreEqual(1, resultItems.Count);
            Assert.AreEqual("test3.txt", resultItems[0].FileName);
            Assert.IsTrue(resultItems[0].FailedToWrite);
            Assert.IsNotEmpty(resultItems[0].ErrorMessage);
        }
Ejemplo n.º 5
0
        protected override void WriteMatch(ICapture capture)
        {
            if (SpellcheckState?.Data.IgnoredValues.Contains(capture.Value) == true)
            {
                return;
            }

            string result = Replacer.Replace(capture);

            if (result != null)
            {
                _textWriter?.Write(Input.AsSpan(_writerIndex, capture.Index - _writerIndex));
                _textWriter?.Write(result);

                _writerIndex = capture.Index + capture.Length;

                ReplacementCount++;
            }

            SpellcheckState?.ProcessReplacement(Input, capture, result);
        }
Ejemplo n.º 6
0
    private static Expression <Func <T, bool> >?CombinePredicates <T>(
        this Expression <Func <T, bool> >?left,
        Expression <Func <T, bool> >?right,
        ExpressionType type)
    {
        if (left == null)
        {
            return(right);
        }
        if (right == null)
        {
            return(left);
        }

        var parameter = Expression.Parameter(typeof(T));

        var l = Replacer.Replace(left, parameter);
        var r = Replacer.Replace(right, parameter);

        var body = Expression.MakeBinary(type, l !, r !);

        return(Expression.Lambda <Func <T, bool> >(body, parameter));
    }
Ejemplo n.º 7
0
        public void Replace_WhenUseEscapeCahrs_RepacesTextInOne()
        {
            Replacer replacer = new Replacer();

            replacer.Dir            = _tempDir;
            replacer.FileMask       = "test6.txt";
            replacer.FindText       = @"\t";
            replacer.ReplaceText    = @"\r\n";
            replacer.UseEscapeChars = true;

            var resultItems = replacer.Replace().ResultItems;

            if (resultItems == null || resultItems.Count == 0)
            {
                Assert.Fail("Can't find test files");
            }

            Assert.AreEqual(1, resultItems.Count);

            Finder finder = new Finder();

            finder.Dir                        = _tempDir;
            finder.FileMask                   = "test6.txt";
            finder.FindText                   = @"\t";
            finder.UseEscapeChars             = true;
            finder.IncludeFilesWithoutMatches = true;

            var findResultItems = finder.Find().Items;

            Assert.AreEqual(1, findResultItems.Count);
            Assert.AreEqual(0, findResultItems[0].Matches.Count);

            finder.FindText = @"\r\n";
            findResultItems = finder.Find().Items;
            Assert.AreEqual(1, findResultItems.Count);
            Assert.AreEqual(3, findResultItems[0].Matches.Count);
        }
Ejemplo n.º 8
0
        private async void RotatingStatuses(object objState)
        {
            try
            {
                var state = (TimerState)objState;

                if (!_bss.Data.RotateStatuses)
                {
                    return;
                }

                IReadOnlyList <RotatingPlayingStatus> rotatingStatuses;
                using (var uow = _db.GetDbContext())
                {
                    rotatingStatuses = uow._context.RotatingStatus
                                       .AsNoTracking()
                                       .OrderBy(x => x.Id)
                                       .ToList();
                }

                if (rotatingStatuses.Count == 0)
                {
                    return;
                }

                var playingStatus = state.Index >= rotatingStatuses.Count
                    ? rotatingStatuses[state.Index = 0]
                    : rotatingStatuses[state.Index++];

                var statusText = _rep.Replace(playingStatus.Status);
                await _bot.SetGameAsync(statusText, playingStatus.Type);
            }
            catch (Exception ex)
            {
                Log.Warning(ex, "Rotating playing status errored: {ErrorMessage}", ex.Message);
            }
        }
Ejemplo n.º 9
0
        public void Replace_WhenSearchTextIsEEAndUseSubDirNoRegExpr_ReplacesTextInFour()
        {
            Replacer replacer = new Replacer();

            replacer.Dir                   = _tempDir;
            replacer.FileMask              = "*.*";
            replacer.FindText              = "ee";
            replacer.ReplaceText           = "!!";
            replacer.IncludeSubDirectories = true;

            var resultItems = replacer.Replace().ResultItems;

            if (resultItems == null || resultItems.Count == 0)
            {
                Assert.Fail("Can't find test files");
            }

            var matchedResultItems = resultItems.Where(ri => ri.NumMatches != 0).ToList();

            Assert.AreEqual(5, matchedResultItems.Count);

            var firstFile = resultItems.Where(ri => ri.FileName == "test1.txt").ToList();

            Assert.AreEqual(2, firstFile.Count);
            Assert.AreEqual(5, firstFile[0].NumMatches);
            Assert.AreEqual(5, firstFile[1].NumMatches);
            Assert.IsTrue(firstFile[0].IsSuccess);
            Assert.IsTrue(firstFile[1].IsSuccess);

            var secondFile = resultItems.Where(ri => ri.FileName == "test2.txt").ToList();

            Assert.AreEqual(2, secondFile.Count);
            Assert.AreEqual(1, secondFile[0].NumMatches);
            Assert.IsTrue(secondFile[0].IsSuccess);
            Assert.AreEqual(1, secondFile[1].NumMatches);
            Assert.IsTrue(secondFile[1].IsSuccess);
        }
Ejemplo n.º 10
0
        protected override void WriteEndMatch(ICapture capture)
        {
            string result = Replacer.Replace(capture);

            WriteReplacement(capture, result);
        }
Ejemplo n.º 11
0
 public static void Main(string[] args)
 {
     var replacer = new Replacer();
     var result = replacer.Replace("Proposal is given to {Jwala Vora#3/13} for {Amazon Vally#2/11} {1#3/75} by {MdOffice employee#1/1}");
     Console.WriteLine(result);
 }
Ejemplo n.º 12
0
        private static double GetPrice(string price, Dictionary <string, double> constants)
        {
            var tokens = Replacer.Replace(constants, Token.GetTokensFromString(price));

            return(new Calculator().Calculate(tokens));
        }
Ejemplo n.º 13
0
        public void TestIsNullStraight()
        {
            string text         = "IsNull(expression)";
            string expectedText = "expression == null";

            var n = _replacer.Replace(text, out _actual);

            Assert.AreEqual(expectedText, _actual);
            Assert.AreEqual(1, n);
        }
 private void OnInsertion(string insertedScript, int caretOffset, int range)
 {
     Replacer.Replace(caretOffset, range, insertedScript);
 }
Ejemplo n.º 15
0
 private void DoReplaceWork()
 {
     _replacer.Replace();
 }
Ejemplo n.º 16
0
        public int Run(string[] args)
        {
            DosErrorLevel dosErrorLevel;

            _options = new CommandLineOptions();
            if (!CommandLine.Parser.Default.ParseArguments(args, _options))
            {
                Console.ReadKey();
                Environment.Exit(1);
            }

            var validationResultList = new List <ValidationResult>();

            validationResultList.Add(ValidationUtils.IsDirValid(_options.Dir, "dir"));
            validationResultList.Add(ValidationUtils.IsNotEmpty(_options.FileMask, "fileMask"));
            validationResultList.Add(ValidationUtils.IsNotEmpty(_options.FindText, "find"));
            validationResultList.Add(ValidationUtils.IsNotEmpty(_options.FindText, "find"));

            if (_options.IsFindTextHasRegEx)
            {
                validationResultList.Add(ValidationUtils.IsValidRegExp(_options.FindText, "find"));
            }

            if (!(String.IsNullOrEmpty(_options.AlwaysUseEncoding)))
            {
                validationResultList.Add(ValidationUtils.IsValidEncoding(_options.AlwaysUseEncoding, "alwaysUseEncoding"));
            }

            if (!(String.IsNullOrEmpty(_options.DefaultEncodingIfNotDetected)))
            {
                validationResultList.Add(ValidationUtils.IsValidEncoding(_options.DefaultEncodingIfNotDetected, "alwaysUseEncoding"));
            }

            if (_options.UseEscapeChars)
            {
                validationResultList.Add(ValidationUtils.IsValidEscapeSequence(_options.FindText, "find"));

                if (!String.IsNullOrEmpty(_options.ReplaceText))
                {
                    validationResultList.Add(ValidationUtils.IsValidEscapeSequence(_options.ReplaceText, "replace"));
                }
            }


            if (!String.IsNullOrEmpty(_options.LogFile))
            {
                var fs1 = new FileStream(_options.LogFile, FileMode.Create);
                var sw1 = new StreamWriter(fs1);
                Console.SetOut(sw1);
            }

            Console.WriteLine("");

            if (validationResultList.Any(vr => !vr.IsSuccess))
            {
                foreach (var validationResult in validationResultList)
                {
                    if (!validationResult.IsSuccess)
                    {
                        Console.WriteLine(String.Format("{0}: {1}", validationResult.FieldName, validationResult.ErrorMessage));
                    }
                }

                Console.WriteLine("");

                dosErrorLevel = DosErrorLevel.FatalError;
            }
            else
            {
                dosErrorLevel = DosErrorLevel.Success;

                bool hasRegEx = _options.IsFindTextHasRegEx;

                if (_options.ReplaceText == null)
                {
                    var finder = new Finder();
                    finder.Dir = _options.Dir;
                    finder.IncludeSubDirectories = _options.IncludeSubDirectories;
                    finder.FileMask        = _options.FileMask;
                    finder.ExcludeFileMask = _options.ExcludeFileMask;

                    finder.FindText                   = CommandLineUtils.DecodeText(_options.FindText, false, hasRegEx, _options.UseEscapeChars);
                    finder.IsCaseSensitive            = _options.IsCaseSensitive;
                    finder.FindTextHasRegEx           = hasRegEx;
                    finder.SkipBinaryFileDetection    = _options.SkipBinaryFileDetection;
                    finder.IncludeFilesWithoutMatches = _options.IncludeFilesWithoutMatches;

                    finder.AlwaysUseEncoding            = Utils.GetEncodingByName(_options.AlwaysUseEncoding);
                    finder.DefaultEncodingIfNotDetected = Utils.GetEncodingByName(_options.DefaultEncodingIfNotDetected);
                    finder.UseEscapeChars = _options.UseEscapeChars;

                    finder.IsSilent = _options.Silent;

                    finder.FileProcessed += OnFinderFileProcessed;

                    var findResult = finder.Find();


                    if (_options.SetErrorLevelIfAnyFileErrors)
                    {
                        if (findResult.Stats.Files.FailedToRead > 0)
                        {
                            dosErrorLevel = DosErrorLevel.ErrorsInSomeFiles;
                        }
                    }
                }
                else
                {
                    var replacer = new Replacer();
                    replacer.Dir = _options.Dir;

                    replacer.IncludeSubDirectories = _options.IncludeSubDirectories;

                    replacer.FileMask        = _options.FileMask;
                    replacer.ExcludeFileMask = _options.ExcludeFileMask;

                    replacer.FindText                   = CommandLineUtils.DecodeText(_options.FindText, false, hasRegEx, _options.UseEscapeChars);
                    replacer.IsCaseSensitive            = _options.IsCaseSensitive;
                    replacer.FindTextHasRegEx           = _options.IsFindTextHasRegEx;
                    replacer.SkipBinaryFileDetection    = _options.SkipBinaryFileDetection;
                    replacer.IncludeFilesWithoutMatches = _options.IncludeFilesWithoutMatches;

                    replacer.ReplaceText = CommandLineUtils.DecodeText(_options.ReplaceText, true, _options.IsFindTextHasRegEx, _options.UseEscapeChars);

                    replacer.AlwaysUseEncoding            = Utils.GetEncodingByName(_options.AlwaysUseEncoding);
                    replacer.DefaultEncodingIfNotDetected = Utils.GetEncodingByName(_options.DefaultEncodingIfNotDetected);
                    replacer.UseEscapeChars = _options.UseEscapeChars;

                    replacer.IsSilent = _options.Silent;

                    replacer.FileProcessed += OnReplacerFileProcessed;

                    var replaceResult = replacer.Replace();

                    if (_options.SetErrorLevelIfAnyFileErrors)
                    {
                        if (replaceResult.Stats.Files.FailedToRead > 0 || replaceResult.Stats.Files.FailedToWrite > 0)
                        {
                            dosErrorLevel = DosErrorLevel.ErrorsInSomeFiles;
                        }
                    }
                }
            }

            if (!String.IsNullOrEmpty(_options.LogFile))
            {
                Console.Out.Close();
            }

#if (DEBUG)
            Console.ReadLine();
                        #endif

            return((int)dosErrorLevel);
        }
Ejemplo n.º 17
0
 public void Manage_Dollars_In_Replaced_Word()
 {
     var dict = new StringDictionary { { "tem$p", "temporary" } };
     var replacer = new Replacer(dict);
     Assert.That(replacer.Replace("$tem$p$"), Is.EqualTo("temporary"));
 }
Ejemplo n.º 18
0
        public PlayingRotateService(DiscordSocketClient client, IBotConfigProvider bcp,
                                    DbService db, IDataCache cache, NadekoBot bot, MusicService music)
        {
            _client = client;
            _bcp    = bcp;
            _db     = db;
            _log    = LogManager.GetCurrentClassLogger();
            _cache  = cache;

            if (client.ShardId == 0)
            {
                _rep = new ReplacementBuilder()
                       .WithClient(client)
                       .WithStats(client)
                       .WithMusic(music)
                       .Build();

                _t = new Timer(async(objState) =>
                {
                    try
                    {
                        bcp.Reload();

                        var state = (TimerState)objState;
                        if (!BotConfig.RotatingStatuses)
                        {
                            return;
                        }
                        if (state.Index >= BotConfig.RotatingStatusMessages.Count)
                        {
                            state.Index = 0;
                        }

                        if (!BotConfig.RotatingStatusMessages.Any())
                        {
                            return;
                        }
                        var status = BotConfig.RotatingStatusMessages[state.Index++].Status;
                        if (string.IsNullOrWhiteSpace(status))
                        {
                            return;
                        }

                        status = _rep.Replace(status);

                        try
                        {
                            await bot.SetGameAsync(status).ConfigureAwait(false);
                        }
                        catch (Exception ex)
                        {
                            _log.Warn(ex);
                        }
                    }
                    catch (Exception ex)
                    {
                        _log.Warn("Rotating playing status errored.\n" + ex);
                    }
                }, new TimerState(), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1));
            }
        }
Ejemplo n.º 19
0
 public void Test_Empty()
 {
     var dict = new StringDictionary();
     var replacer = new Replacer(dict);
     Assert.That(replacer.Replace(""), Is.EqualTo(""));
 }
Ejemplo n.º 20
0
 public void Test_One_Word()
 {
     var dict = new StringDictionary { { "temp", "temporary" } };
     var replacer = new Replacer(dict);
     Assert.That(replacer.Replace("$temp$"), Is.EqualTo("temporary"));
 }
Ejemplo n.º 21
0
 public static string GetDocumentPath(this NSwagClientAttribute attribute, Replacer replacer)
 {
     return(replacer.Replace(attribute.DocumentPath));
 }
Ejemplo n.º 22
0
Archivo: Text.cs Proyecto: tspring/ioke
        public override void Init(IokeObject obj)
        {
            Runtime runtime = obj.runtime;

            obj.Kind = "Text";
            obj.Mimics(IokeObject.As(IokeObject.FindCell(runtime.Mixins, "Comparing"), null), runtime.nul, runtime.nul);

            obj.RegisterMethod(runtime.NewNativeMethod("returns a hash for the text",
                                                       new NativeMethod.WithNoArguments("hash", (method, context, message, on, outer) => {
                outer.ArgumentsDefinition.CheckArgumentCount(context, message, on);
                return(context.runtime.NewNumber(((Text)IokeObject.dataOf(on)).text.GetHashCode()));
            })));

            obj.RegisterMethod(runtime.NewNativeMethod("returns true if the left hand side text is equal to the right hand side text.",
                                                       new TypeCheckingNativeMethod("==", TypeCheckingArgumentsDefinition.builder()
                                                                                    .ReceiverMustMimic(runtime.Text)
                                                                                    .WithRequiredPositional("other")
                                                                                    .Arguments,
                                                                                    (method, on, args, keywords, context, message) => {
                Text d       = (Text)IokeObject.dataOf(on);
                object other = args[0];

                return(((other is IokeObject) &&
                        (IokeObject.dataOf(other) is Text) &&
                        ((on == context.runtime.Text || other == context.runtime.Text) ? on == other :
                         d.text.Equals(((Text)IokeObject.dataOf(other)).text))) ? context.runtime.True : context.runtime.False);
            })));

            obj.RegisterMethod(runtime.NewNativeMethod("Returns a text representation of the object",
                                                       new NativeMethod.WithNoArguments("asText",
                                                                                        (method, context, message, on, outer) => {
                outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, new SaneArrayList(), new SaneDictionary <string, object>());
                return(on);
            })));

            obj.RegisterMethod(runtime.NewNativeMethod("Takes any number of arguments, and expects the text receiver to contain format specifications. The currently supported specifications are only %s and %{, %}. These have several parameters that can be used. See the spec for more info about these. The format method will return a new text based on the content of the receiver, and the arguments given.",
                                                       new TypeCheckingNativeMethod("format", TypeCheckingArgumentsDefinition.builder()
                                                                                    .ReceiverMustMimic(obj)
                                                                                    .WithRest("replacements")
                                                                                    .Arguments,
                                                                                    (self, on, args, keywords, context, message) => {
                StringBuilder result = new StringBuilder();
                Format(on, message, context, args, result);
                return(context.runtime.NewText(result.ToString()));
            })));


            obj.RegisterMethod(obj.runtime.NewNativeMethod("Converts the content of this text into a rational value",
                                                           new TypeCheckingNativeMethod.WithNoArguments("toRational", obj,
                                                                                                        (self, on, args, keywords, context, message) => {
                return(Text.ToRational(on, context, message));
            })));

            obj.RegisterMethod(obj.runtime.NewNativeMethod("Converts the content of this text into a decimal value",
                                                           new TypeCheckingNativeMethod.WithNoArguments("toDecimal", obj,
                                                                                                        (self, on, args, keywords, context, message) => {
                return(Text.ToDecimal(on, context, message));
            })));

            obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns a text inspection of the object",
                                                           new TypeCheckingNativeMethod.WithNoArguments("inspect", obj,
                                                                                                        (self, on, args, keywords, context, message) => {
                return(self.runtime.NewText(Text.GetInspect(on)));
            })));

            obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns a brief text inspection of the object",
                                                           new TypeCheckingNativeMethod.WithNoArguments("notice", obj,
                                                                                                        (self, on, args, keywords, context, message) => {
                return(self.runtime.NewText(Text.GetInspect(on)));
            })));

            obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns a text where all non-safe characters have been replaced with safe ones",
                                                           new TypeCheckingNativeMethod.WithNoArguments("makeXMLSafe", obj,
                                                                                                        (self, on, args, keywords, context, message) => {
                return(self.runtime.NewText(new StringUtils().XmlSafe(Text.GetText(on))));
            })));

            obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns a lower case version of this text",
                                                           new TypeCheckingNativeMethod.WithNoArguments("lower", obj,
                                                                                                        (self, on, args, keywords, context, message) => {
                return(self.runtime.NewText(Text.GetText(on).ToLower()));
            })));

            obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns an upper case version of this text",
                                                           new TypeCheckingNativeMethod.WithNoArguments("upper", obj,
                                                                                                        (self, on, args, keywords, context, message) => {
                return(self.runtime.NewText(Text.GetText(on).ToUpper()));
            })));

            obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns a version of this text with leading and trailing whitespace removed",
                                                           new TypeCheckingNativeMethod.WithNoArguments("trim", obj,
                                                                                                        (self, on, args, keywords, context, message) => {
                return(self.runtime.NewText(Text.GetText(on).Trim()));
            })));

            obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns an array of texts split around the argument",
                                                           new TypeCheckingNativeMethod("split", TypeCheckingArgumentsDefinition.builder()
                                                                                        .ReceiverMustMimic(obj)
                                                                                        .WithOptionalPositional("splitAround", "")
                                                                                        .Arguments,
                                                                                        (self, on, args, keywords, context, message) => {
                string real = Text.GetText(on);
                var r       = new SaneArrayList();
                Pattern p   = null;

                if (args.Count == 0)
                {
                    p = new Pattern("\\s");
                }
                else
                {
                    object arg = args[0];
                    if (IokeObject.dataOf(arg) is Regexp)
                    {
                        p = Regexp.GetRegexp(arg);
                    }
                    else
                    {
                        string around = Text.GetText(arg);
                        p             = new Pattern(Pattern.Quote(around));
                    }
                }

                RETokenizer tok  = new RETokenizer(p, real);
                tok.EmptyEnabled = false;
                while (tok.HasMore)
                {
                    r.Add(context.runtime.NewText(tok.NextToken));
                }

                return(context.runtime.NewList(r));
            })));

            obj.RegisterMethod(obj.runtime.NewNativeMethod("Takes two text arguments where the first is the substring to replace, and the second is the replacement to insert. Will only replace the first match, if any is found, and return a new Text with the result.",
                                                           new TypeCheckingNativeMethod("replace", TypeCheckingArgumentsDefinition.builder()
                                                                                        .ReceiverMustMimic(obj)
                                                                                        .WithRequiredPositional("pattern")
                                                                                        .WithRequiredPositional("replacement")
                                                                                        .Arguments,
                                                                                        (self, on, args, keywords, context, message) => {
                string initial = Text.GetText(on);
                string repl    = Text.GetText(args[1]);

                object arg = args[0];

                Pattern pat = null;
                if (IokeObject.dataOf(arg) is Regexp)
                {
                    pat = Regexp.GetRegexp(arg);
                }
                else
                {
                    string around = Text.GetText(arg);
                    pat           = new Pattern(Pattern.Quote(around));
                }

                Replacer r    = pat.Replacer(repl);
                string result = r.ReplaceFirst(initial);

                return(context.runtime.NewText(result));
            })));

            obj.RegisterMethod(obj.runtime.NewNativeMethod("Takes two text arguments where the first is the substring to replace, and the second is the replacement to insert. Will replace all matches, if any is found, and return a new Text with the result.",
                                                           new TypeCheckingNativeMethod("replaceAll", TypeCheckingArgumentsDefinition.builder()
                                                                                        .ReceiverMustMimic(obj)
                                                                                        .WithRequiredPositional("pattern")
                                                                                        .WithRequiredPositional("replacement")
                                                                                        .Arguments,
                                                                                        (self, on, args, keywords, context, message) => {
                string initial = Text.GetText(on);
                string repl    = Text.GetText(args[1]);

                object arg = args[0];

                Pattern pat = null;
                if (IokeObject.dataOf(arg) is Regexp)
                {
                    pat = Regexp.GetRegexp(arg);
                }
                else
                {
                    string around = Text.GetText(arg);
                    pat           = new Pattern(Pattern.Quote(around));
                }

                Replacer r    = pat.Replacer(repl);
                String result = r.Replace(initial);

                return(context.runtime.NewText(result));
            })));

            obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns the length of this text",
                                                           new TypeCheckingNativeMethod.WithNoArguments("length", obj,
                                                                                                        (self, on, args, keywords, context, message) => {
                return(context.runtime.NewNumber(GetText(on).Length));
            })));

            obj.RegisterMethod(obj.runtime.NewNativeMethod("compares this text against the argument, returning -1, 0 or 1 based on which one is lexically larger",
                                                           new TypeCheckingNativeMethod("<=>", TypeCheckingArgumentsDefinition.builder()
                                                                                        .ReceiverMustMimic(obj)
                                                                                        .WithRequiredPositional("other")
                                                                                        .Arguments,
                                                                                        (self, on, args, keywords, context, message) => {
                object arg = args[0];

                if (!(IokeObject.dataOf(arg) is Text))
                {
                    arg = IokeObject.ConvertToText(arg, message, context, false);
                    if (!(IokeObject.dataOf(arg) is Text))
                    {
                        // Can't compare, so bail out
                        return(context.runtime.nil);
                    }
                }

                if (on == context.runtime.Text || arg == context.runtime.Text)
                {
                    if (on == arg)
                    {
                        return(context.runtime.NewNumber(0));
                    }
                    return(context.runtime.nil);
                }

                int result = string.CompareOrdinal(Text.GetText(on), Text.GetText(arg));
                if (result < 0)
                {
                    result = -1;
                }
                else if (result > 0)
                {
                    result = 1;
                }

                return(context.runtime.NewNumber(result));
            })));

            obj.RegisterMethod(obj.runtime.NewNativeMethod("takes one argument, that can be either an index or a range of two indicis. this slicing works the same as for Lists, so you can index from the end, both with the single index and with the range.",
                                                           new TypeCheckingNativeMethod("[]", TypeCheckingArgumentsDefinition.builder()
                                                                                        .ReceiverMustMimic(obj)
                                                                                        .WithRequiredPositional("index")
                                                                                        .Arguments,
                                                                                        (self, on, args, keywords, context, message) => {
                object arg    = args[0];
                IokeData data = IokeObject.dataOf(arg);

                if (data is Range)
                {
                    int first = Number.ExtractInt(Range.GetFrom(arg), message, context);

                    if (first < 0)
                    {
                        return(context.runtime.NewText(""));
                    }

                    int last       = Number.ExtractInt(Range.GetTo(arg), message, context);
                    bool inclusive = Range.IsInclusive(arg);

                    string str = GetText(on);
                    int size   = str.Length;

                    if (last < 0)
                    {
                        last = size + last;
                    }

                    if (last < 0)
                    {
                        return(context.runtime.NewText(""));
                    }

                    if (last >= size)
                    {
                        last = inclusive ? size - 1 : size;
                    }

                    if (first > last || (!inclusive && first == last))
                    {
                        return(context.runtime.NewText(""));
                    }

                    if (!inclusive)
                    {
                        last--;
                    }

                    return(context.runtime.NewText(str.Substring(first, (last + 1) - first)));
                }
                else if (data is Number)
                {
                    string str = GetText(on);
                    int len    = str.Length;

                    int ix = ((Number)data).AsNativeInteger();

                    if (ix < 0)
                    {
                        ix = len + ix;
                    }

                    if (ix >= 0 && ix < len)
                    {
                        return(context.runtime.NewNumber(str[ix]));
                    }
                    else
                    {
                        return(context.runtime.nil);
                    }
                }

                return(on);
            })));

            obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns a symbol representing the Unicode category of the character",
                                                           new TypeCheckingNativeMethod.WithNoArguments("category", obj,
                                                                                                        (self, on, args, keywords, context, message) => {
                string character = GetText(on);
                if (character.Length == 1)
                {
                    return(context.runtime.GetSymbol(UnicodeBlock.Of(character[0])));
                }

                IokeObject condition = IokeObject.As(IokeObject.GetCellChain(runtime.Condition,
                                                                             message,
                                                                             context,
                                                                             "Error",
                                                                             "Default"), context).Mimic(message, context);
                condition.SetCell("message", message);
                condition.SetCell("context", context);
                condition.SetCell("receiver", on);
                condition.SetCell("text", context.runtime.NewText("Text does not contain exactly one character"));

                runtime.ErrorCondition(condition);
                return(null);
            })));
            obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns a new text where all the escapes in the current text have been evaluated - exactly as if another parsing step had been applied. This does not evaluate embedded code, though.",
                                                           new TypeCheckingNativeMethod.WithNoArguments("evaluateEscapes", obj,
                                                                                                        (self, on, args, keywords, context, message) => {
                return(context.runtime.NewText(new StringUtils().ReplaceEscapes(GetText(on))));
            })));
        }