public CSharpIndentEngine(IDocument document, TextEditorOptions textEditorOptions, CSharpFormattingOptions formattingOptions) { this.document = document; this.options = formattingOptions; this.textEditorOptions = textEditorOptions; this.indent = new Indent(textEditorOptions); this.thisLineindent = new Indent(textEditorOptions); }
/// <summary> /// Test an indentor /// </summary> /// <param name="indentor">A class implementing Indent</param> public void test(Indent indentor) { foreach(TestItem item in m_Items) { doTest(item, indentor); } printResults(); }
/// <summary> /// Do a test of a TestItem /// </summary> /// <param name="item">the item to test</param> /// <param name="indentor">the indentor to use</param> private void doTest(TestItem item, Indent indentor) { string contents_original = loadContents(item.getOriginal()); string contents_indented = indentor.indent(contents_original); string contents_gold = loadContents(item.getIndeted()); if (contentsEqual(contents_indented, contents_gold)) { m_Passing.Add(item); } else { m_Failing.Add(item); } }
CSharpIndentEngine (CSharpIndentEngine prototype) { this.document = prototype.document; this.options = prototype.options; this.textEditorOptions = prototype.textEditorOptions; this.indent = prototype.indent.Clone(); this.thisLineindent = prototype.thisLineindent.Clone(); this.offset = prototype.offset; this.inside = prototype.inside; this.IsLineStart = prototype.IsLineStart; this.pc = prototype.pc; this.parenStack = new Stack<TextLocation>(prototype.parenStack.Reverse ()); this.currentBody = prototype.currentBody; this.nextBody = prototype.nextBody; this.addContinuation = prototype.addContinuation; this.line = prototype.line; this.col = prototype.col; this.popNextParenBlock = prototype.popNextParenBlock; }
public void AddPorcelain <ApiClient>(CommandLineApplication app, IClientFactory <ApiClient> clientFactory) { var properties = clientFactory.GetProperties(); properties.ToList().ForEach(prop => { var groupType = prop.PropertyType; var groupName = groupType.Name.Substring(0, groupType.Name.Length - 3).Substring(1); var methods = groupType.GetMethods(); methods.ToList().ForEach(m => { var methodName = m.Name; var commandName = $"{methodName}".ToKebabCase(); if (commandName.EndsWith("-")) { commandName = commandName.Substring(0, commandName.Length - 1); } var parameters = m.GetParameters().Where(param => !param.Name.ToLower().Equals("useragent")); app.Command(commandName, (command) => { command.Description = $"Porcelain command for {methodName.ToText()} Api"; command.HelpOption("-?|-h|--help"); // standard options var apiToken = new Token(); var apiTokenOption = command.Option(apiToken.Template, apiToken.Description, apiToken.OptionType); var indent = new Indent(); command.Option(indent.Template, indent.Description, indent.OptionType); var outputPath = new OutputPath(); command.Option(outputPath.Template, outputPath.Description, outputPath.OptionType); var filter = new Filter(); command.Option(filter.Template, filter.Description, filter.OptionType); var options = new List <CommandOption>(); parameters.ToList().ForEach(param => { var paramName = $"--{param.Name}"; var paramDesc = $"The {param.Name}"; var option = command.Option(paramName, paramDesc, CommandOptionType.SingleValue); options.Add(option); }); command.OnExecute(() => { return(command.Run( app, () => { var client = clientFactory.GetClient(apiTokenOption.Value()); var api = GetApi(client, prop); var method = api.GetType().GetMethod(m.Name); List <object> args = CompileRequestArgs <ApiClient>(app, clientFactory, options); return InvokeRequest(api, method, args); } )); }); }); }); }); }
public static void Generate(IEnumerable <ApiParent> apis, TextWriter writer) { writer.Write(@"// This file was automatically generated by CoreTweet. // Do not modify this file directly. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Linq.Expressions; using CoreTweet.Core; #if !NET35 using System.Threading; using System.Threading.Tasks; #endif namespace CoreTweet.Rest { "); var ind = new Indent(1); foreach (var i in apis) { writer.WriteLine(ind + "/// <summary>"); writer.WriteLine(ind + "/// {0}", i.Description); writer.WriteLine(ind + "/// </summary>"); writer.WriteLine(ind + "public partial class {0} : ApiProviderBase", i.Name); writer.WriteLine(ind + "{"); ind.Inc(); writer.WriteLine(ind + "internal " + i.Name + "(TokensBase e) : base(e) { }"); writer.WriteLine(""); foreach (var j in i.Endpoints) { if (j is RawLines) { foreach (var l in (j as RawLines).Lines) { writer.WriteLine(ind + l); } writer.WriteLine(""); continue; } writer.WriteLine(ind + "#if !(PCL || WIN_RT || WP)"); foreach (var m in j.Methods) { var @when = m.WhenClause; if (@when != null) { writer.WriteLine(ind + "#if " + @when); } writer.WriteLine(ind + "/// <summary>"); foreach (var k in j.Description) { writer.WriteLine(ind + "/// <para>" + k + "</para>"); } var prms = m.Params.Distinct(new ParameterNameComparer()).ToArray(); if (!m.HasStaticArgs) { if (prms.Length > 0) { writer.WriteLine(ind + "/// <para>Available parameters:</para>"); foreach (var k in prms) { writer.WriteLine(ind + "/// <para>- <c>{0}</c> {1} ({2})</para>", k.Type.Replace("<", "<").Replace(">", ">"), k.RealName, k.Kind); } } else { writer.WriteLine(ind + "/// <para>Available parameters: Nothing.</para>"); } } writer.WriteLine(ind + "/// </summary>"); if (m.HasStaticArgs) { foreach (var k in prms) { writer.WriteLine(ind + "/// <param name=\"{0}\">{1}.</param>", k.RealName, k.Kind); } } else { writer.WriteLine(ind + "/// <param name=\"parameters\">The parameters.</param>"); } if (m.Definition.Contains("EnumerateMode mode")) { writer.WriteLine(ind + "/// <param name=\"mode\">Specify whether enumerating goes to the next page or the previous.</param>"); } writer.WriteLine(ind + "/// <returns>{0}</returns>", j.Returns); foreach (var a in j.Attributes) { writer.WriteLine(ind + "[{0}(\"{1}\")]", a.Item1, a.Item2); } writer.WriteLine(ind + m.Definition); writer.WriteLine(ind + "{"); ind.Inc(); foreach (var l in m.Body) { writer.WriteLine(ind + l); } ind.Dec(); writer.WriteLine(ind + "}"); if (@when != null) { writer.WriteLine(ind + "#endif"); } writer.WriteLine(""); } writer.WriteLine(ind + "#endif"); writer.WriteLine(ind + "#if !NET35"); writer.WriteLine(""); foreach (var m in j.MethodsAsync) { var @when = m.WhenClause; if (@when != null) { writer.WriteLine(ind + "#if " + @when); } writer.WriteLine(ind + "/// <summary>"); foreach (var k in j.Description) { writer.WriteLine(ind + "/// <para>" + k + "</para>"); } var prms = m.Params.Distinct(new ParameterNameComparer()).ToArray(); if (!m.HasStaticArgs) { writer.WriteLine(ind + "/// <para>Available parameters:</para>"); foreach (var k in prms) { writer.WriteLine(ind + "/// <para>- <c>{0}</c> {1} ({2})</para>", k.Type.Replace("<", "<").Replace(">", ">"), k.RealName, k.Kind); } } writer.WriteLine(ind + "/// </summary>"); if (m.HasStaticArgs) { foreach (var k in prms) { writer.WriteLine(ind + "/// <param name=\"{0}\">{1}.</param>", k.RealName, k.Kind); } } else { writer.WriteLine(ind + "/// <param name=\"parameters\">The parameters.</param>"); } if (m.TakesCancellationToken) { writer.WriteLine(ind + "/// <param name=\"cancellationToken\">The cancellation token.</param>"); } writer.WriteLine(ind + "/// <returns>{0}</returns>", j.Returns); writer.WriteLine(ind + m.Definition); writer.WriteLine(ind + "{"); ind.Inc(); foreach (var l in m.Body) { writer.WriteLine(ind + l); } ind.Dec(); writer.WriteLine(ind + "}"); if (@when != null) { writer.WriteLine(ind + "#endif"); } writer.WriteLine(""); } writer.WriteLine(ind + "#endif"); writer.WriteLine(""); } ind.Dec(); writer.WriteLine(ind + "}"); writer.WriteLine(""); } writer.WriteLine('}'); }
public static void Notify(Indent indent) { var json = Mapper.Map <IndentJson>(indent); Notify(Json.Encode(json), GetEntityName(indent)); }
private string GenerateEnumerableMethodForBatchApiEndpoint(ApiEndpoint apiEndpoint, string baseEndpointPath) { var indent = new Indent(); var builder = new StringBuilder(); var endpointPath = (baseEndpointPath + "/" + apiEndpoint.Path.Segments.ToPath()).TrimEnd('/'); var methodNameForEndpoint = apiEndpoint.ToCSharpMethodName(); var batchDataType = ((ApiFieldType.Object)apiEndpoint.ResponseBody !).GetBatchDataType() !; if (apiEndpoint.ResponseBody != null) { var methodParametersBuilder = new MethodParametersBuilder(_codeGenerationContext) .WithParametersForApiParameters(apiEndpoint.Parameters); if (apiEndpoint.RequestBody != null) { if (FeatureFlags.DoNotExposeRequestObjects) { methodParametersBuilder = methodParametersBuilder .WithParametersForApiFields(apiEndpoint.RequestBody.Fields); } else { methodParametersBuilder = methodParametersBuilder .WithParameter( apiEndpoint.ToCSharpRequestBodyClassName(endpointPath) !, "data"); } } var partialType = "Partial<" + batchDataType.GetBatchElementTypeOrType().ToCSharpType(_codeGenerationContext) + ">"; var funcType = $"Func<{partialType}, {partialType}>?"; methodParametersBuilder = methodParametersBuilder .WithParameter( funcType, "partial", CSharpExpression.NullLiteral); methodParametersBuilder = methodParametersBuilder .WithParameter(CSharpType.CancellationToken.Value, "cancellationToken", CSharpExpression.DefaultLiteral); builder.Append( indent.Wrap(GenerateMethodDocumentationForEndpoint(apiEndpoint))); builder.Append($"{indent}public IAsyncEnumerable<"); builder.Append(batchDataType.ElementType.ToCSharpType(_codeGenerationContext)); builder.Append(">"); builder.Append($" {methodNameForEndpoint}AsyncEnumerable("); builder.Append(methodParametersBuilder.BuildMethodParametersList()); builder.AppendLine(")"); indent.Increment(); builder.Append($"{indent}=> BatchEnumerator.AllItems((batchSkip, batchCancellationToken) => "); builder.Append($"{methodNameForEndpoint}Async("); var partialTypeForBatch = "Partial<Batch<" + batchDataType.GetBatchElementTypeOrType().ToCSharpType(_codeGenerationContext) + ">>"; builder.Append( methodParametersBuilder .WithDefaultValueForAllParameters(null) .WithDefaultValueForParameter("skip", "batchSkip") .WithDefaultValueForParameter("partial", $"builder => {partialTypeForBatch}.Default().WithNext().WithTotalCount().WithData(partial != null ? partial : _ => {partialType}.Default())") .WithDefaultValueForParameter(CSharpType.CancellationToken.Value, "batchCancellationToken") .BuildMethodCallParameters()); builder.Append("), skip, cancellationToken);"); indent.Decrement(); } else { builder.AppendLine($"{indent}#warning UNSUPPORTED CASE - " + apiEndpoint.ToCSharpMethodName() + " - " + apiEndpoint.Method.ToHttpMethod() + " " + endpointPath); } return(builder.ToString()); }
private string GenerateMethodForApiEndpoint(ApiEndpoint apiEndpoint, string baseEndpointPath) { var indent = new Indent(); var builder = new StringBuilder(); var endpointPath = (baseEndpointPath + "/" + apiEndpoint.Path.Segments.ToPath()).TrimEnd('/'); var apiCallMethod = apiEndpoint.Method.ToHttpMethod(); var methodNameForEndpoint = apiEndpoint.ToCSharpMethodName(); var isResponsePrimitiveOrArrayOfPrimitive = apiEndpoint.ResponseBody is ApiFieldType.Primitive || (apiEndpoint.ResponseBody is ApiFieldType.Array arrayField && arrayField.ElementType is ApiFieldType.Primitive); if (apiEndpoint.ResponseBody == null) { var methodParametersBuilder = new MethodParametersBuilder(_codeGenerationContext) .WithParametersForApiParameters(apiEndpoint.Parameters); if (apiEndpoint.RequestBody != null) { if (FeatureFlags.DoNotExposeRequestObjects) { methodParametersBuilder = methodParametersBuilder .WithParametersForApiFields(apiEndpoint.RequestBody.Fields); } else { methodParametersBuilder = methodParametersBuilder .WithParameter( apiEndpoint.ToCSharpRequestBodyClassName(endpointPath) !, "data"); } } methodParametersBuilder = methodParametersBuilder .WithParameter(CSharpType.CancellationToken.Value, "cancellationToken", CSharpExpression.DefaultLiteral); builder.Append( indent.Wrap(GenerateMethodDocumentationForEndpoint(apiEndpoint))); builder.Append($"{indent}public async Task {methodNameForEndpoint}Async("); builder.Append(methodParametersBuilder.BuildMethodParametersList()); builder.AppendLine(")"); builder.AppendLine($"{indent}{{"); indent.Increment(); // Generate query string var requestParametersBuilder = new QueryStringParameterConversionGenerator("queryParameters", _codeGenerationContext) .WithQueryStringParametersForEndpoint(apiEndpoint); if (apiEndpoint.ResponseBody != null && !isResponsePrimitiveOrArrayOfPrimitive) { var partialType = "Partial<" + apiEndpoint.ResponseBody.GetArrayElementTypeOrType().ToCSharpType(_codeGenerationContext) + ">"; requestParametersBuilder = requestParametersBuilder .WithQueryStringParameter("$fields", $"(partial != null ? partial(new {partialType}()) : {partialType}.Default()).ToString()"); } builder.AppendLine($"{indent}var {requestParametersBuilder.TargetNameValueCollectionName} = new NameValueCollection();"); requestParametersBuilder.WriteTo(builder, indent); builder.AppendLine($"{indent}"); // Generate HTTP request builder.Append($"{indent}await _connection.RequestResourceAsync"); builder.Append("(\"" + apiCallMethod + "\", "); builder.Append("$\"api/http/" + endpointPath + "{" + requestParametersBuilder.TargetNameValueCollectionName + ".ToQueryString()}"); builder.Append("\""); if (apiEndpoint.RequestBody != null) { if (FeatureFlags.DoNotExposeRequestObjects) { // TODO MAARTEN REFACTOR WITH PROPER NEWLINES builder.Append(", " + ConstructNewRequestObject(indent, apiEndpoint, endpointPath)); } else { builder.Append(", data"); } } builder.Append(", cancellationToken"); builder.AppendLine(");"); indent.Decrement(); builder.AppendLine($"{indent}}}"); } else if (apiEndpoint.ResponseBody != null) { var methodParametersBuilder = new MethodParametersBuilder(_codeGenerationContext) .WithParametersForApiParameters(apiEndpoint.Parameters); if (apiEndpoint.RequestBody != null) { if (FeatureFlags.DoNotExposeRequestObjects) { methodParametersBuilder = methodParametersBuilder .WithParametersForApiFields(apiEndpoint.RequestBody.Fields); } else { methodParametersBuilder = methodParametersBuilder .WithParameter( apiEndpoint.ToCSharpRequestBodyClassName(endpointPath) !, "data"); } } if (apiEndpoint.ResponseBody != null && !isResponsePrimitiveOrArrayOfPrimitive) { var partialType = "Partial<" + apiEndpoint.ResponseBody.GetArrayElementTypeOrType().ToCSharpType(_codeGenerationContext) + ">"; var funcType = $"Func<{partialType}, {partialType}>?"; methodParametersBuilder = methodParametersBuilder .WithParameter( funcType, "partial", CSharpExpression.NullLiteral); } methodParametersBuilder = methodParametersBuilder .WithParameter(CSharpType.CancellationToken.Value, "cancellationToken", CSharpExpression.DefaultLiteral); builder.Append( indent.Wrap(GenerateMethodDocumentationForEndpoint(apiEndpoint))); builder.Append($"{indent}public async Task<"); builder.Append(apiEndpoint.ResponseBody !.ToCSharpType(_codeGenerationContext)); builder.Append(">"); builder.Append($" {methodNameForEndpoint}Async("); builder.Append(methodParametersBuilder.BuildMethodParametersList()); builder.AppendLine(")"); builder.AppendLine($"{indent}{{"); indent.Increment(); // Generate query string var requestParametersBuilder = new QueryStringParameterConversionGenerator("queryParameters", _codeGenerationContext) .WithQueryStringParametersForEndpoint(apiEndpoint); if (apiEndpoint.ResponseBody != null && !isResponsePrimitiveOrArrayOfPrimitive) { var partialType = "Partial<" + apiEndpoint.ResponseBody.GetArrayElementTypeOrType().ToCSharpType(_codeGenerationContext) + ">"; requestParametersBuilder = requestParametersBuilder .WithQueryStringParameter("$fields", $"(partial != null ? partial(new {partialType}()) : {partialType}.Default()).ToString()"); } builder.AppendLine($"{indent}var {requestParametersBuilder.TargetNameValueCollectionName} = new NameValueCollection();"); requestParametersBuilder.WriteTo(builder, indent); builder.AppendLine($"{indent}"); // Generate HTTP request builder.Append($"{indent}return await _connection.RequestResourceAsync<"); if (apiEndpoint.RequestBody != null) { builder.Append(apiEndpoint.ToCSharpRequestBodyClassName(endpointPath) !); builder.Append(", "); } builder.Append(apiEndpoint.ResponseBody !.ToCSharpType(_codeGenerationContext)); builder.Append(">"); builder.Append("(\"" + apiCallMethod + "\", "); builder.Append("$\"api/http/" + endpointPath + "{" + requestParametersBuilder.TargetNameValueCollectionName + ".ToQueryString()}"); builder.Append("\""); if (apiEndpoint.RequestBody != null) { if (FeatureFlags.DoNotExposeRequestObjects) { builder.Append(", " + ConstructNewRequestObject(indent, apiEndpoint, endpointPath)); } else { builder.Append(", data"); } } builder.Append(", cancellationToken"); builder.AppendLine(");"); indent.Decrement(); builder.AppendLine($"{indent}}}"); } else { builder.AppendLine($"{indent}#warning UNSUPPORTED CASE - " + apiEndpoint.ToCSharpMethodName() + " - " + apiEndpoint.Method.ToHttpMethod() + " " + endpointPath); } return(builder.ToString()); }
public void MultipleIndents_AreMixed() { LineToDeltaConverter .Parse("> 1. * A") .Is( new Ops() .Insert("A") .Insert(new LineInsert( new LineFormat( new List <Indent>() { Indent.Quote, Indent.Empty(1), Indent.Number(2), Indent.Empty(1), Indent.Bullet, Indent.Empty(1) }, 0) ) ) ); LineToDeltaConverter .Parse("- > 1. A") .Is( new Ops() .Insert("A") .Insert(new LineInsert( new LineFormat( new List <Indent>() { Indent.Bullet, Indent.Empty(2), Indent.Quote, Indent.Empty(2), Indent.Number(2), Indent.Empty(2) }, 0) ) ) ); LineToDeltaConverter .Parse(">>> A") .Is( new Ops() .Insert("A") .Insert(new LineInsert( new LineFormat( new List <Indent>() { Indent.Quote, Indent.Quote, Indent.Quote, Indent.Empty(1) }, 0) ) ) ); }
public static Ops Parse(string line) { var ops = new Ops(); var lineFormat = new LineFormat(); string text = line; var indentMatch = indentRegex.Match(text); int?codeMatch = null; while (indentMatch.Groups["indent"].Success) { var indentType = Indent.Empty(0); if (indentMatch.Groups["whitespace"].Success) { int length = indentMatch.Groups["whitespace"].Length; if (length % 4 == 0) { indentType = Indent.Code; codeMatch = length; } else { indentType = Indent.Empty(length); } } else if (indentMatch.Groups["quotes"].Success) { indentType = Indent.Quote; } else if (indentMatch.Groups["horizontalrule"].Success) { return(ops.Insert(new DividerInsert()).Insert(new LineInsert(lineFormat))); } else if (indentMatch.Groups["bullet"].Success) { indentType = Indent.Bullet; } else if (indentMatch.Groups["number"].Success) { indentType = Indent.Number(indentMatch.Groups["number"].Length); } if (indentType is not null) { lineFormat.Indents.Add(indentType); } text = indentMatch.Groups["text"].Value; if (codeMatch is not null) { // text = text.Insert(0, String.Concat(Enumerable.Repeat(" ", (int)codeMatch / 4 - 1))); break; } indentMatch = indentRegex.Match(text); } if (codeMatch is null) { var headerMatch = headerRegex.Match(text); if (headerMatch.Groups["header"].Success) { lineFormat.Header = headerMatch.Groups["header"].Value.Length; } text = headerMatch.Groups["text"].Value; } var textOps = LinksAndImagesWithTextToDelta(text); ops.InsertMany(textOps); ops.Insert(new LineInsert(lineFormat)); return(ops); }
public static void PushIndent(string indent) { Indent.Add(indent); }
private static void PrintArg(IArgument argument, Indent indent, Action <string> writeln) { bool isObscured = argument.IsObscured(); var indent2 = indent.Increment(); var txtValue = Resources.A.Common_value_lc; var txtInputs = Resources.A.Input_inputs_lc; var txtDefault = Resources.A.Common_default_lc; var displayName = argument.TypeInfo.DisplayName.IsNullOrEmpty() ? (((argument as Option)?.IsFlag ?? false) ? Resources.A.Common_Flag : null) : argument.TypeInfo.DisplayName; writeln($"{indent}{argument.Name} <{displayName}>"); var valueString = argument.Value?.ValueToString(argument); writeln(valueString == null ? $"{indent2}{txtValue}:" : $"{indent2}{txtValue}: {valueString}"); if (!argument.InputValues.IsNullOrEmpty()) { var pwd = isObscured ? Password.ValueReplacement : null; var values = argument.InputValues .Select(iv => iv.Source == Resources.A.Common_argument_lc && argument.InputValues.Count == 1 ? $"{ValuesToString(iv, pwd)}" : iv.IsStream ? $"[{iv.Source} {Resources.A.Input_stream_lc}]" : $"[{iv.Source}] {ValuesToString(iv, pwd)}") .ToList(); if (values.Count == 1) { writeln($"{indent2}{txtInputs}: {values.Single()}"); } else { writeln($"{indent2}{txtInputs}:"); values.ForEach(v => writeln($"{indent2.Increment()}{v}")); } } else { writeln($"{indent2}{txtInputs}:"); } if (argument.Default != null) { // don't include source when the default is defined as a parameter or property. // only show externally defined sources writeln(argument.Default.Source.StartsWith("app.") ? $"{indent2}{txtDefault}: " + $"{argument.Default.Value.ValueToString(argument)}" : $"{indent2}{txtDefault}: " + $"{Resources.A.Common_source_lc}={argument.Default.Source} " + $"{Resources.A.Common_key_lc}={argument.Default.Key}: " + $"{argument.Default.Value.ValueToString(argument)}"); } else { writeln($"{indent2}{txtDefault}:"); } }
void Push(char ch) { if (readPreprocessorExpression) { wordBuf.Append(ch); } if (inside.HasFlag (Inside.VerbatimString) && pc == '"' && ch != '"') { inside &= ~Inside.String; } switch (ch) { case '#': if (IsLineStart) inside = Inside.PreProcessor; break; case '/': if (IsInStringOrChar || IsInPreProcessorComment) break; if (pc == '/') { if (inside.HasFlag (Inside.Comment)) { inside |= Inside.DocComment; } else { inside |= Inside.Comment; } } break; case '*': if (IsInStringOrChar || IsInComment || IsInPreProcessorComment) break; if (pc == '/') inside |= Inside.MultiLineComment; break; case '\t': var nextTabStop = (col - 1 + textEditorOptions.IndentSize) / textEditorOptions.IndentSize; col = 1 + nextTabStop * textEditorOptions.IndentSize; return; case '\r': if (readPreprocessorExpression) { if (!eval (wordBuf.ToString ())) inside |= Inside.PreProcessorComment; } inside &= ~(Inside.Comment | Inside.String | Inside.CharLiteral | Inside.PreProcessor); CheckKeyword(wordBuf.ToString()); wordBuf.Length = 0; if (addContinuation) { indent.Push (IndentType.Continuation); } thisLineindent = indent.Clone (); addContinuation = false; IsLineStart = true; readPreprocessorExpression = false; col = 1; line++; break; case '\n': if (pc == '\r') break; goto case '\r'; case '"': if (IsInComment || IsInPreProcessorComment) break; if (inside.HasFlag (Inside.String)) { if (pc != '\\') inside &= ~Inside.String; break; } if (pc =='@') { inside |= Inside.VerbatimString; } else { inside |= Inside.String; } break; case '<': case '[': case '(': if (IsInComment || IsInStringOrChar || IsInPreProcessorComment) break; parenStack.Push (new TextLocation (line, col)); popNextParenBlock = true; indent.Push (IndentType.Block); break; case '>': case ']': case ')': if (IsInComment || IsInStringOrChar || IsInPreProcessorComment) break; if (popNextParenBlock) parenStack.Pop (); indent.Pop (); indent.ExtraSpaces = 0; break; case ',': if (IsInComment || IsInStringOrChar || IsInPreProcessorComment) break; if (parenStack.Count > 0 && parenStack.Peek ().Line == line) { indent.Pop (); popNextParenBlock = false; indent.ExtraSpaces = parenStack.Peek ().Column - 1 - thisLineindent.CurIndent; } break; case '{': if (IsInComment || IsInStringOrChar || IsInPreProcessorComment) break; currentBody = nextBody; if (indent.Count > 0 && indent.Peek() == IndentType.Continuation) indent.Pop(); addContinuation = false; AddIndentation (currentBody); break; case '}': if (IsInComment || IsInStringOrChar || IsInPreProcessorComment) break; indent.Pop (); if (indent.Count > 0 && indent.Peek() == IndentType.Continuation) indent.Pop(); break; case ';': if (IsInComment || IsInStringOrChar || IsInPreProcessorComment) break; if (indent.Count > 0 && indent.Peek() == IndentType.Continuation) indent.Pop(); break; case '\'': if (IsInComment || inside.HasFlag (Inside.String) || IsInPreProcessorComment) break; if (inside.HasFlag (Inside.CharLiteral)) { if (pc != '\\') inside &= ~Inside.CharLiteral; } else { inside &= Inside.CharLiteral; } break; } if (!IsInComment && !IsInStringOrChar && !readPreprocessorExpression) { if ((wordBuf.Length == 0 ? char.IsLetter(ch) : char.IsLetterOrDigit(ch)) || ch == '_') { wordBuf.Append(ch); } else { if (inside.HasFlag (Inside.PreProcessor)) { if (wordBuf.ToString () == "endif") { inside &= ~Inside.PreProcessorComment; } else if (wordBuf.ToString () == "if") { readPreprocessorExpression = true; } else if (wordBuf.ToString () == "elif") { inside &= ~Inside.PreProcessorComment; readPreprocessorExpression = true; } } else { CheckKeyword(wordBuf.ToString()); } wordBuf.Length = 0; } } if (addContinuation) { indent.Push (IndentType.Continuation); addContinuation = false; } IsLineStart &= ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r'; pc = ch; if (ch != '\n' && ch != '\r') col++; }
/// <summary>Returns an Indent with <see cref="Depth"/>+1<br/></summary> public Indent Increment() => _nextDepth ?? (_nextDepth = new Indent(this));
public AstFormattingVisitor(CSharpFormattingOptions policy, IDocument document, TextEditorOptions options = null) { if (policy == null) { throw new ArgumentNullException("policy"); } if (document == null) { throw new ArgumentNullException("document"); } this.policy = policy; this.document = document; this.options = options ?? TextEditorOptions.Default; curIndent = new Indent(this.options); }
public static void Generate(IEnumerable<ApiParent> apis, TextWriter writer) { writer.Write(@"// This file was automatically generated by CoreTweet. // Do not modify this file directly. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Linq.Expressions; using CoreTweet.Core; #if ASYNC using System.Threading; using System.Threading.Tasks; #endif #pragma warning disable RECS0163 namespace CoreTweet.Rest { "); var ind = new Indent(1); foreach (var i in apis) { writer.WriteLine(ind + "/// <summary>"); writer.WriteLine(ind + "/// {0}", i.Description); writer.WriteLine(ind + "/// </summary>"); writer.WriteLine(ind + "public partial class {0} : ApiProviderBase", i.Name); writer.WriteLine(ind + "{"); ind.Inc(); writer.WriteLine(ind + "internal " + i.Name + "(TokensBase e) : base(e) { }"); writer.WriteLine(""); foreach (var j in i.Endpoints) { if (j is RawLines) { foreach (var l in (j as RawLines).Lines) writer.WriteLine(ind + l); writer.WriteLine(""); continue; } writer.WriteLine(ind + "#if SYNC"); foreach (var m in j.Methods) { var @when = m.WhenClause; if (@when != null) writer.WriteLine(ind + "#if " + @when); writer.WriteLine(ind + "/// <summary>"); foreach (var k in j.Description) writer.WriteLine(ind + "/// <para>" + k + "</para>"); var prms = m.Params.Distinct(new ParameterNameComparer()).ToArray(); if (!m.HasStaticArgs) { if (prms.Length > 0) { writer.WriteLine(ind + "/// <para>Available parameters:</para>"); foreach (var k in prms) writer.WriteLine(ind + "/// <para>- <c>{0}</c> {1} ({2})</para>", k.Type.Replace("<", "<").Replace(">", ">"), k.RealName, k.Kind); } else { writer.WriteLine(ind + "/// <para>Available parameters: Nothing.</para>"); } } writer.WriteLine(ind + "/// </summary>"); if (m.HasStaticArgs) foreach (var k in prms) writer.WriteLine(ind + "/// <param name=\"{0}\">{1}.</param>", k.RealName, k.Kind); else writer.WriteLine(ind + "/// <param name=\"parameters\">The parameters.</param>"); if (m.Definition.Contains("EnumerateMode mode")) writer.WriteLine(ind + "/// <param name=\"mode\">Specify whether enumerating goes to the next page or the previous.</param>"); writer.WriteLine(ind + "/// <returns>{0}</returns>", j.Returns); foreach (var a in j.Attributes) writer.WriteLine(ind + "[{0}(\"{1}\")]", a.Item1, a.Item2); writer.WriteLine(ind + m.Definition); writer.WriteLine(ind + "{"); ind.Inc(); foreach (var l in m.Body) writer.WriteLine(ind + l); ind.Dec(); writer.WriteLine(ind + "}"); if (@when != null) writer.WriteLine(ind + "#endif"); writer.WriteLine(""); } writer.WriteLine(ind + "#endif"); writer.WriteLine(ind + "#if ASYNC"); writer.WriteLine(""); foreach (var m in j.MethodsAsync) { var @when = m.WhenClause; if (@when != null) writer.WriteLine(ind + "#if " + @when); writer.WriteLine(ind + "/// <summary>"); foreach (var k in j.Description) writer.WriteLine(ind + "/// <para>" + k + "</para>"); var prms = m.Params.Distinct(new ParameterNameComparer()).ToArray(); if (!m.HasStaticArgs) { writer.WriteLine(ind + "/// <para>Available parameters:</para>"); foreach (var k in prms) writer.WriteLine(ind + "/// <para>- <c>{0}</c> {1} ({2})</para>", k.Type.Replace("<", "<").Replace(">", ">"), k.RealName, k.Kind); } writer.WriteLine(ind + "/// </summary>"); if (m.HasStaticArgs) foreach (var k in prms) writer.WriteLine(ind + "/// <param name=\"{0}\">{1}.</param>", k.RealName, k.Kind); else writer.WriteLine(ind + "/// <param name=\"parameters\">The parameters.</param>"); if (m.TakesCancellationToken) writer.WriteLine(ind + "/// <param name=\"cancellationToken\">The cancellation token.</param>"); writer.WriteLine(ind + "/// <returns>{0}</returns>", j.Returns); writer.WriteLine(ind + m.Definition); writer.WriteLine(ind + "{"); ind.Inc(); foreach (var l in m.Body) writer.WriteLine(ind + l); ind.Dec(); writer.WriteLine(ind + "}"); if (@when != null) writer.WriteLine(ind + "#endif"); writer.WriteLine(""); } writer.WriteLine(ind + "#endif"); writer.WriteLine(""); } ind.Dec(); writer.WriteLine(ind + "}"); writer.WriteLine(""); } writer.WriteLine('}'); }
public void Push(char ch) { var isNewLine = NewLine.IsNewLine(ch); if (!isNewLine) { if (ch == '"') { isInString = !IsInsideString; if (isInString) { savedStringIndent = nextLineIndent; nextLineIndent = new Indent(ctx.GetOptionSet()); } else { nextLineIndent = savedStringIndent; } } if (ch == '{' || ch == '[') { nextLineIndent.Push(IndentType.Block); } else if (ch == '}' || ch == ']') { if (thisLineIndent.Count > 0) { thisLineIndent.Pop(); } if (nextLineIndent.Count > 0) { nextLineIndent.Pop(); } } } else { if (ch == NewLine.LF && previousChar == NewLine.CR) { offset++; previousChar = ch; return; } } offset++; if (!isNewLine) { // previousNewline = '\0'; isLineStart &= char.IsWhiteSpace(ch); if (isLineStart) { currentIndent.Append(ch); } if (ch == '\t') { var nextTabStop = (column - 1 + editor.Options.IndentationSize) / editor.Options.IndentationSize; column = 1 + nextTabStop * editor.Options.IndentationSize; } else { column++; } } else { // previousNewline = ch; currentIndent.Length = 0; isLineStart = true; column = 1; line++; thisLineIndent = nextLineIndent.Clone(); } previousChar = ch; }
public int AddIndent(Indent Ix) { return(dal.AddIndent(Ix)); }
public string ToString(Indent indent) { return(this.ToStringFromPublicProperties(indent)); }
public static void PopIndent() { Indent.Remove(Indent.Last()); }
public int SaveIndent(Indent indent) { return(this.DataContext.SaveIndent(indent)); }
public static void Notify(int indentId) { Indent indent = IndentRepository.GetIndent(indentId); NotificationService.NotifyAll(indent); }
public string ToString(Indent indent) => this.ToStringFromPublicProperties(indent);
public static void Report(CommandContext commandContext, Action <string> writeln, Indent indent = null) { Diagnostics.Parse.ParseReporter.Report(commandContext, writeln, indent); }
private static void OnPreferencesGUI() { scroll = EditorGUILayout.BeginScrollView(scroll, false, false); EditorGUILayout.Separator(); Enabled.DoGUI(); EditorGUILayout.Separator(); EditorGUILayout.HelpBox("Each item has a tooltip explaining what it does, keep the mouse over it to see.", MessageType.Info); EditorGUILayout.Separator(); using (Enabled.GetEnabledScope()) { using (new GUIIndent("Misc settings")) { using (new GUIIndent("Margins")) { RightMargin.DoGUISlider(-50, 50); LeftMargin.DoGUISlider(-50, 50); Indent.DoGUISlider(0, 35); } Tree.DoGUI(); using (new GUIIndent()) using (SelectOnTree.GetFadeScope(Tree)) SelectOnTree.DoGUI(); Tooltips.DoGUI(); using (new GUIIndent()) using (RelevantTooltipsOnly.GetFadeScope(Tooltips)) RelevantTooltipsOnly.DoGUI(); EnhancedSelection.DoGUI(); Trailing.DoGUI(); ChangeAllSelected.DoGUI(); NumericChildExpand.DoGUI(); using (HideDefaultIcon.GetFadeScope(IsButtonEnabled(new Icons.GameObjectIcon()))) HideDefaultIcon.DoGUI(); GUI.changed = false; using (AllowSelectingLocked.GetFadeScope(IsButtonEnabled(new Icons.Lock()))) AllowSelectingLocked.DoGUI(); using (AllowSelectingLockedSceneView.GetFadeScope(IsButtonEnabled(new Icons.Lock()) && AllowSelectingLocked)) AllowSelectingLockedSceneView.DoGUI(); if (GUI.changed && EditorUtility.DisplayDialog("Relock all objects", "Would you like to relock all objects?\n" + "This is recommended when changing this setting and might take a few seconds on large scenes" + "\nIt's also recommended to do this on all scenes", "Yes", "No")) { Utility.RelockAllObjects(); } HoverTintColor.DoGUI(); } using (new GUIIndent("Row separators")) { LineSize.DoGUISlider(0, 6); using (LineColor.GetFadeScope(LineSize > 0)) LineColor.DoGUI(); OddRowColor.DoGUI(); EvenRowColor.DoGUI(); GUI.changed = false; var rect = EditorGUILayout.GetControlRect(false, rowColorsList.GetHeight()); rect.xMin += EditorGUI.indentLevel * 16f; rowColorsList.DoList(rect); } MiniLabel.DoGUI(); using (new GUIIndent()) { using (SmallerMiniLabel.GetFadeScope(MiniLabel.Value != MiniLabelType.None)) SmallerMiniLabel.DoGUI(); using (HideDefaultTag.GetFadeScope(MiniLabelTagEnabled)) HideDefaultTag.DoGUI(); using (HideDefaultLayer.GetFadeScope(MiniLabelLayerEnabled)) HideDefaultLayer.DoGUI(); using (CentralizeMiniLabelWhenPossible.GetFadeScope((HideDefaultLayer || HideDefaultTag) && (MiniLabel.Value == MiniLabelType.TagAndLayer || MiniLabel.Value == MiniLabelType.LayerAndTag))) CentralizeMiniLabelWhenPossible.DoGUI(); } LeftSideButtonPref.DoGUI(); using (new GUIIndent()) using (LeftmostButton.GetFadeScope(LeftSideButton != IconBase.rightNone)) LeftmostButton.DoGUI(); using (new GUIIndent("Children behaviour on change")) { using (LockAskMode.GetFadeScope(IsButtonEnabled(new Icons.Lock()))) LockAskMode.DoGUI(); using (LayerAskMode.GetFadeScope(IsButtonEnabled(new Icons.Layer()) || MiniLabelLayerEnabled)) LayerAskMode.DoGUI(); using (TagAskMode.GetFadeScope(IsButtonEnabled(new Icons.Tag()) || MiniLabelTagEnabled)) TagAskMode.DoGUI(); using (StaticAskMode.GetFadeScope(IsButtonEnabled(new Icons.Static()))) StaticAskMode.DoGUI(); using (IconAskMode.GetFadeScope(IsButtonEnabled(new Icons.GameObjectIcon()))) IconAskMode.DoGUI(); EditorGUILayout.HelpBox(string.Format("Pressing down {0} while clicking on a button will make it temporary have the opposite children change mode", Utility.CtrlKey), MessageType.Info); } leftIconsList.displayAdd = LeftIconsMenu.GetItemCount() > 0; leftIconsList.DoLayoutList(); rightIconsList.displayAdd = RightIconsMenu.GetItemCount() > 0; rightIconsList.DoLayoutList(); EditorGUILayout.HelpBox("Alt + Click on child expand toggle makes it expand all the grandchildren too", MessageType.Info); if (IsButtonEnabled(new Icons.Memory())) { EditorGUILayout.HelpBox("\"Memory Used\" may create garbage and consequently framerate stutterings, leave it disabled if maximum performance is important for your project", MessageType.Warning); } if (IsButtonEnabled(new Icons.Lock())) { EditorGUILayout.HelpBox("Remember to always unlock your game objects when removing or disabling this extension, as you won't be able to unlock without it and may lose scene data", MessageType.Warning); } GUI.enabled = true; EditorGUILayout.EndScrollView(); using (new EditorGUILayout.HorizontalScope()) { GUILayout.FlexibleSpace(); EditorGUILayout.LabelField(versionContent, GUILayout.Width(170f)); } using (new EditorGUILayout.HorizontalScope()) { if (GUILayout.Button(resetSettingsContent, GUILayout.Width(120f))) { onResetPreferences(); } if (GUILayout.Button(unlockAllContent, GUILayout.Width(120f))) { Utility.UnlockAllObjects(); } if (GUILayout.Button(mailDeveloperContent, GUILayout.Width(120f))) { Application.OpenURL(GetEmailURL()); } } EditorGUILayout.Separator(); Styles.ReloadTooltips(); EditorApplication.RepaintHierarchyWindow(); } }
private string GenerateResourceDefinition( ApiResource apiResource, string typeNameForClient, string baseEndpointPath, string resourceBreadcrumbPath, HashSet <string> resourceBreadcrumbPaths, bool withConstructor) { var indent = new Indent(); var builder = new StringBuilder(); // Client class builder.AppendLine($"{indent}public partial class {typeNameForClient} : ISpaceClient"); builder.AppendLine($"{indent}{{"); indent.Increment(); // Constructor needed? if (withConstructor) { builder.AppendLine($"{indent}private readonly Connection _connection;"); builder.AppendLine($"{indent}"); builder.AppendLine($"{indent}public {typeNameForClient}(Connection connection)"); builder.AppendLine($"{indent}{{"); indent.Increment(); builder.AppendLine($"{indent}_connection = connection;"); indent.Decrement(); builder.AppendLine($"{indent}}}"); builder.AppendLine($"{indent}"); } // Endpoint methods foreach (var apiEndpoint in apiResource.Endpoints) { builder.AppendLine( indent.Wrap( GenerateMethodsForApiEndpoint(apiEndpoint, baseEndpointPath))); } // Group nested resources by path var pathToResourceMapper = new PathToResourceMapper(); var mapOfPathToResources = pathToResourceMapper.CreateMapOfPathToResources(apiResource); foreach (var(_, apiNestedResources) in mapOfPathToResources) { var isFirstResource = true; foreach (var apiNestedResource in apiNestedResources) { var nestedResourceBreadcrumbPath = (resourceBreadcrumbPath.Length > 0 ? resourceBreadcrumbPath + "." : resourceBreadcrumbPath) + apiNestedResource.ToCSharpIdentifierSingular(); var typeNameForNestedClient = apiNestedResource.ToCSharpIdentifierSingular() + "Client"; if (typeNameForNestedClient == typeNameForClient) { // Example: Team Directory > Profiles > Profiles > Deactivate -> ProfileProfileClient typeNameForNestedClient = apiNestedResource.ToCSharpIdentifierSingular() + apiNestedResource.ToCSharpIdentifierSingular() + "Client"; } var isFirstWrite = resourceBreadcrumbPaths.Add(nestedResourceBreadcrumbPath); if (isFirstResource && isFirstWrite) { var propertyNameForNestedClient = apiNestedResource.ToCSharpIdentifierPlural(); builder.AppendLine($"{indent}public {typeNameForNestedClient} {propertyNameForNestedClient} => new {typeNameForNestedClient}(_connection);"); builder.AppendLine($"{indent}"); } builder.AppendLine( indent.Wrap( GenerateResourceDefinition( apiNestedResource, typeNameForNestedClient, (baseEndpointPath.Length > 0 ? baseEndpointPath + "/" : baseEndpointPath) + apiNestedResource.Path.Segments.ToPath(), nestedResourceBreadcrumbPath, resourceBreadcrumbPaths, isFirstResource && isFirstWrite))); isFirstResource = false; } } indent.Decrement(); builder.AppendLine($"{indent}}}"); return(builder.ToString()); }
private void Awake() { this.indent = new Indent(); this.strings = new List <string>(); }
private static void OnPreferencesGUI(string search) { scroll = EditorGUILayout.BeginScrollView(scroll, false, false); EditorGUILayout.Separator(); Enabled.DoGUI(); EditorGUILayout.Separator(); EditorGUILayout.HelpBox("Each item has a tooltip explaining what it does, keep the mouse over it to see.", MessageType.Info); EditorGUILayout.Separator(); using (Enabled.GetEnabledScope()) { using (new GUIIndent("Misc settings")) { using (new GUIIndent("Margins")) { RightMargin.DoGUISlider(-50, 50); using (new GUIEnabled(Reflected.HierarchyArea.Supported)) { LeftMargin.DoGUISlider(-50, 50); Indent.DoGUISlider(0, 35); } if (!Reflected.HierarchyArea.Supported) { EditorGUILayout.HelpBox("Custom Indent and Margins are not supported in this Unity version", MessageType.Warning); } } IconsSize.DoGUISlider(13, 23); TreeOpacity.DoGUISlider(0f, 1f); using (new GUIIndent()) { using (SelectOnTree.GetFadeScope(TreeOpacity.Value > 0.01f)) SelectOnTree.DoGUI(); using (TreeStemProportion.GetFadeScope(TreeOpacity.Value > 0.01f)) TreeStemProportion.DoGUISlider(0f, 1f); } Tooltips.DoGUI(); using (new GUIIndent()) using (RelevantTooltipsOnly.GetFadeScope(Tooltips)) RelevantTooltipsOnly.DoGUI(); if (EnhancedSelectionSupported) { EnhancedSelection.DoGUI(); } Trailing.DoGUI(); ChangeAllSelected.DoGUI(); NumericChildExpand.DoGUI(); using (new GUIEnabled(Reflected.IconWidthSupported)) DisableNativeIcon.DoGUI(); using (HideDefaultIcon.GetFadeScope(IsButtonEnabled(new Icons.GameObjectIcon()))) HideDefaultIcon.DoGUI(); using (OpenScriptsOfLogs.GetFadeScope(IsButtonEnabled(new Icons.Warnings()))) OpenScriptsOfLogs.DoGUI(); GUI.changed = false; using (AllowSelectingLockedObjects.GetFadeScope(IsButtonEnabled(new Icons.Lock()))) AllowSelectingLockedObjects.DoGUI(); #if !UNITY_2019_3_OR_NEWER using (new GUIEnabled(false)) #endif using (AllowPickingLockedObjects.GetFadeScope(IsButtonEnabled(new Icons.Lock()))) AllowPickingLockedObjects.DoGUI(); HoverTintColor.DoGUI(); } using (new GUIIndent("Row separators")) { LineSize.DoGUISlider(0, 6); using (LineColor.GetFadeScope(LineSize > 0)) LineColor.DoGUI(); OddRowColor.DoGUI(); EvenRowColor.DoGUI(); GUI.changed = false; var rect = EditorGUILayout.GetControlRect(false, rowColorsList.GetHeight()); rect.xMin += EditorGUI.indentLevel * 16f; rowColorsList.DoList(rect); } GUI.changed = false; MiniLabels.Value[0] = EditorGUILayout.Popup("Mini Label Top", MiniLabels.Value[0], minilabelsNames); MiniLabels.Value[1] = EditorGUILayout.Popup("Mini Label Bottom", MiniLabels.Value[1], minilabelsNames); if (GUI.changed) { MiniLabels.ForceSave(); RecreateMiniLabelProviders(); } // MiniLabel.DoGUI(); using (new GUIIndent()) { using (SmallerMiniLabel.GetFadeScope(miniLabelProviders.Length > 0)) SmallerMiniLabel.DoGUI(); using (HideDefaultTag.GetFadeScope(MiniLabelTagEnabled)) HideDefaultTag.DoGUI(); using (HideDefaultLayer.GetFadeScope(MiniLabelLayerEnabled)) HideDefaultLayer.DoGUI(); using (CentralizeMiniLabelWhenPossible.GetFadeScope(miniLabelProviders.Length >= 2)) CentralizeMiniLabelWhenPossible.DoGUI(); } LeftSideButtonPref.DoGUI(); using (new GUIIndent()) using (LeftmostButton.GetFadeScope(LeftSideButton != IconBase.none)) LeftmostButton.DoGUI(); using (new GUIIndent("Children behaviour on change")) { using (LockAskMode.GetFadeScope(IsButtonEnabled(new Icons.Lock()))) LockAskMode.DoGUI(); using (LayerAskMode.GetFadeScope(IsButtonEnabled(new Icons.Layer()) || MiniLabelLayerEnabled)) LayerAskMode.DoGUI(); using (TagAskMode.GetFadeScope(IsButtonEnabled(new Icons.Tag()) || MiniLabelTagEnabled)) TagAskMode.DoGUI(); using (StaticAskMode.GetFadeScope(IsButtonEnabled(new Icons.Static()))) StaticAskMode.DoGUI(); using (IconAskMode.GetFadeScope(IsButtonEnabled(new Icons.GameObjectIcon()))) IconAskMode.DoGUI(); EditorGUILayout.HelpBox(string.Format("Pressing down {0} while clicking on a button will make it temporary have the opposite children change mode", Utility.CtrlKey), MessageType.Info); } leftIconsList.displayAdd = LeftIconsMenu.GetItemCount() > 0; leftIconsList.DoLayoutList(); rightIconsList.displayAdd = RightIconsMenu.GetItemCount() > 0; rightIconsList.DoLayoutList(); EditorGUILayout.HelpBox("Alt + Click on child expand toggle makes it expand all the grandchildren too", MessageType.Info); if (IsButtonEnabled(new Icons.Memory())) { EditorGUILayout.HelpBox("\"Memory Used\" may create garbage and consequently framerate stutterings, leave it disabled if maximum performance is important for your project", MessageType.Warning); } if (IsButtonEnabled(new Icons.Lock())) { EditorGUILayout.HelpBox("Remember to always unlock your game objects when removing or disabling this extension, as you won't be able to unlock without it and may lose scene data", MessageType.Warning); } GUI.enabled = true; EditorGUILayout.EndScrollView(); using (new EditorGUILayout.HorizontalScope()) { GUILayout.FlexibleSpace(); EditorGUILayout.LabelField(versionContent, GUILayout.Width(170f)); } using (new EditorGUILayout.HorizontalScope()) { if (GUILayout.Button(resetSettingsContent, GUILayout.Width(120f))) { onResetPreferences(); } // if (GUILayout.Button(unlockAllContent, GUILayout.Width(120f))) // Utility.UnlockAllObjects(); if (GUILayout.Button(mailDeveloperContent, GUILayout.Width(120f))) { OpenSupportEmail(); } } EditorGUILayout.Separator(); Styles.ReloadTooltips(); EditorApplication.RepaintHierarchyWindow(); } }
/// <summary> /// Dumps the specified object as a text tree to the specified <see cref="TextWriter"/>, /// allowing additional user provided primitive types. /// </summary> /// <typeparam name="T">Additional primitive types, implementing <see cref="IPrimitiveTypes"/></typeparam> /// <param name="o">The object to dump.</param> /// <param name="tw">The TextWriter output.</param> /// <param name="ind">The indentation.</param> /// <param name="flags">Output modifier flags.</param> /// <param name="caption">The optional caption for this indentation level.</param> public static void Dump <T> (this object o, TextWriter tw, Indent ind = null, EDumpFlags flags = default, string caption = null) where T : IPrimitiveTypes, new() => TreeDecomposition <T> .Default.Dump(o, tw, ind ?? new Indent(), flags, caption);
public string ToString(Indent indent) { return(indent.Value + this); }
/* * private Token attributes() { Attribute tok = new Attribute(null, lineno); * var matcher = JadeScanner.getMatcherForPattern("^\\("); if * (matcher.find(0)) { consume(matcher[0].Length); attributeMode = true; } else * { return null; } * * StringBuilder sb = new StringBuilder(); String regexp = * "^[, ]*?([-_\\w]+)? *?= *?(\"[^\"]*?\"|'[^']*?'|[.-_\\w]+)"; matcher = * JadeScanner.getMatcherForPattern(regexp); if (matcher.find(0)) { while * (matcher.find(0)) { String name = matcher[0].Groups[1].Value; String value = * matcher[0].Groups[2].Value; tok.addAttribute(name, value); * sb.append(matcher.group(0)); consume(matcher[0].Length); matcher = * JadeScanner.getMatcherForPattern(regexp); } tok.setValue(sb.toString()); } * else { return null; } * * matcher = JadeScanner.getMatcherForPattern("^ *?\\)"); if (matcher.find(0)) { * consume(matcher[0].Length); attributeMode = false; } else { throw new * JadeLexerException * ("Error while parsing attribute. Missing closing bracket ", filename, * getLineno(), JadeScanner.getInput()); } return tok; } */ private Token indent() { MatchCollection matcher; String re; if (indentRe != null) { matcher = _jadeScanner.getMatcherForPattern(indentRe); } else { // tabs re = "^\\n(\\t*) *"; String indentType = "tabs"; matcher = _jadeScanner.getMatcherForPattern(re); // spaces if (matcher.Count > 0 && matcher[0].Groups[1].Value.Length == 0) { re = "^\\n( *)"; indentType = "spaces"; matcher = _jadeScanner.getMatcherForPattern(re); } // established if (matcher.Count > 0 && matcher[0].Groups[1].Value.Length > 0) { this.indentRe = re; } this.indentType = indentType; } if (matcher.Count > 0 && matcher[0].Success && matcher[0].Groups.Count > 0) { Token tok; int indents = matcher[0].Groups[1].Value.Length; if (lastIndents <= 0 && indents > 0) { lastIndents = indents; } lineno++; consume(indents + 1); if ((indents > 0 && lastIndents > 0 && indents % lastIndents != 0) || _jadeScanner.isIntendantionViolated()) { throw new JadeLexerException("invalid indentation; expecting " + indents + " " + indentType, filename, getLineno(), templateLoader); } // blank line if (_jadeScanner.isBlankLine()) { return(new Newline("newline", lineno)); } // outdent if (indentStack.Count > 0 && indents < indentStack.First.Value) { while (indentStack.Count > 0 && indentStack.First.Value > indents) { indentStack.poll(); } stash.AddLast(new Outdent("outdent", lineno)); tok = this.stash.pollLast(); // indent } else if (indents > 0 && (indentStack.Count < 1 || indents != indentStack.First.Value)) { indentStack.AddLast(indents); tok = new Indent("indent", lineno); tok.setIndents(indents); // newline } else { tok = new Newline("newline", lineno); } return(tok); } return(null); }
public void MultipleIndents_WorkInside() { DeltaTree .Parse( new Ops() .Insert("A") .Insert(new LineInsert(LineFormat.NumberPreset)) .Insert("B") .Insert(new LineInsert( new LineFormat( new List <Indent>() { Indent.Number(2), Indent.Bullet }, 0 ) )) .Insert("C") .Insert(new LineInsert( new LineFormat( new List <Indent>() { Indent.Number(2), Indent.Bullet, Indent.Quote }, 0 ) )) .Insert("D") .Insert(new LineInsert( new LineFormat( new List <Indent>() { Indent.Number(2), Indent.Bullet }, 0 ) )) ) .Is( new Container(new List <TreeNode>() { new NumbersContainer(new List <TreeNode>() { new TextLeaf(new List <TextInsert>() { new TextInsert("A") }), new BulletsContainer(new List <TreeNode>() { new TextLeaf(new List <TextInsert>() { new TextInsert("B") }), new QuoteContainer(new List <TreeNode>() { new TextLeaf(new List <TextInsert>() { new TextInsert("C") }), }), new TextLeaf(new List <TextInsert>() { new TextInsert("D") }) }) }) }) ); }
/// <summary> /// RTF paragraph style constructor with just alignment and indent /// <seealso cref="RTFExporter.Alignment"> /// <seealso cref="RTFExporter.Indent"> /// </summary> /// <param name="alignment">Alignment object</param> /// <param name="indent">Indent object</param> public RTFParagraphStyle(Alignment alignment, Indent indent) { this.alignment = alignment; this.indent = indent; }
public WordInfo GetNomEntity(string word, List <Nom> checkedNoms, string fullWord) { WordInfo result = new WordInfo(); IQueryable <Nom> noms = context.Nom1.Where(x => x.reestr.StartsWith(word.ToLower())); if (checkedNoms.Count() > 0) { noms = noms.Except(checkedNoms); } Nom potentialResult = noms.FirstOrDefault(x => x.reestr == fullWord); if (potentialResult != null) { result.nom = potentialResult; result.indent = context.Indents.FirstOrDefault(x => x.type == potentialResult.@type); return(result); } if (noms == null || noms.Count() == 0) { return(GetNomEntity(word.Remove(word.Length - 1), checkedNoms, fullWord)); } else { foreach (Nom nom in noms) { Indent indentOfNewWord = context.Indents.FirstOrDefault(x => x.type == nom.@type); string newWord = String.Empty; if (indentOfNewWord.indent > 0) { newWord = nom.reestr.Remove(nom.reestr.Length - indentOfNewWord.indent); } else { newWord = nom.reestr; } if (!word.StartsWith(newWord)) { continue; } if (newWord == fullWord) { result.nom = nom; result.indent = indentOfNewWord; break; } IQueryable <Flex> flexes = context.Flexes.Where(x => x.type == nom.type && x.flex.Length == (fullWord.Length - newWord.Length)); NomFlex res = new NomFlex(); if (flexes.Count() > 0) { res = GetAllPossibleFlexes(newWord, flexes.ToList(), fullWord, nom.reestr); } if (res != null && res.nom != null && res.nom.reestr != null) { result.nom = res.nom; result.indent = indentOfNewWord; result.flex = res.flex; continue; } } } if (result.nom == null && word.Length > 1) { return(GetNomEntity(word.Remove(word.Length - 1), noms.Concat(checkedNoms).ToList(), fullWord)); } return(result); }
public static void WriteLine(string line) { string indentString = Indent.Aggregate(string.Empty, (current, indent) => current + indent); Writer.WriteLine(indentString + line); }
private static void BuildCode(StringBuilder sb, object instance, Indent indent) { if (instance == null) { sb.Append("null"); return; } var instanceType = instance.GetType(); if (instanceType.IsEnum) { sb.Append(instanceType.FullName).Append(".").Append(instance); return; } if (instanceType.Equals(typeof(DateTime))) { var dt = (DateTime)instance; sb.Append(String.Format("new System.DateTime({0}, {1}, {2}, {3}, {4}, {5}, {6})", dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, dt.Millisecond)); return; } if (instanceType.Equals(typeof(Decimal))) { sb.Append(instance).Append("m"); return; } if (instanceType.Equals(typeof(string))) { sb.Append("\"").Append(instance).Append("\""); return; } if (instanceType.IsValueType) { sb.Append(instance); return; } sb.AppendLine(String.Format("new {0}()", instanceType.FullName.Replace("+", "."))); sb.AppendLine("{"); var properties = TypeDescriptor.GetProperties(instance) .OfType<PropertyDescriptor>() .OrderBy(p => p.Name); indent.Increase(); foreach (PropertyDescriptor property in properties) { var propertyType = property.PropertyType; if (typeof(IList).IsAssignableFrom(propertyType)) { sb.Append(property.Name).Append(" = "); var genericArguments = propertyType.GetGenericArguments(); var list = (IList)property.GetValue(instance); if (list == null) { sb.AppendLine("null, "); } else if (propertyType.Equals(typeof(byte[]))) { var bytes = (byte[])list; sb.AppendLine(String.Format("Convert.FromBase64String(\"{0}\")", Convert.ToBase64String(bytes))); } else { if (genericArguments.Length == 0) { sb.Append("new ").Append(propertyType.GetElementType().FullName).AppendLine("[]"); } else { var listType = genericArguments[0]; sb.Append("new System.Collections.Generic.List<").Append(listType.FullName).AppendLine(">"); } sb.Append("{"); foreach (var thisInstance in list) { //sb.AppendLine("{"); indent.Increase(); BuildCode(sb, thisInstance, indent); indent.Decrease(); //sb.AppendLine("},"); sb.AppendLine(", "); } sb.AppendLine("},"); } } else if (!property.IsReadOnly) { sb.Append(property.Name).Append(" = "); BuildCode(sb, property.GetValue(instance), indent); sb.AppendLine(","); } } indent.Decrease(); sb.Append("}"); }
private string GenerateDtoFieldDefinition(string typeNameForDto, ApiField apiField) { var indent = new Indent(); var builder = new StringBuilder(); var propertyNameForField = apiField.ToCSharpPropertyName(typeNameForDto); var backingFieldNameForField = apiField.ToCSharpBackingFieldName(); // Backing field builder.Append($"{indent}private PropertyValue<"); builder.Append(apiField.Type.ToCSharpType(_codeGenerationContext)); if (apiField.Type.Nullable) { builder.Append("?"); } builder.Append("> "); builder.Append($"{backingFieldNameForField} = new PropertyValue<"); builder.Append(apiField.Type.ToCSharpType(_codeGenerationContext)); if (apiField.Type.Nullable) { builder.Append("?"); } // For non-nullable List<> and Dictionary<>, make sure the field is initialized. // We do this by setting a temporary default value for this pass. var overrideDefaultValue = !apiField.Type.Nullable && apiField.DefaultValue == null; if (overrideDefaultValue) { // TODO When switching to records (.NET 6 LTS), replace this construct to be immutable. apiField.DefaultValue = apiField.Type switch { ApiFieldType.Array _ => new ApiDefaultValue.Collection(), ApiFieldType.Map _ => new ApiDefaultValue.Map(), _ => apiField.DefaultValue }; } var initialValueForAssignment = apiField.ToCSharpDefaultValueForAssignment(_codeGenerationContext); if (initialValueForAssignment != null) { builder.AppendLine($">(nameof({typeNameForDto}), nameof({propertyNameForField}), {initialValueForAssignment});"); } else { builder.AppendLine($">(nameof({typeNameForDto}), nameof({propertyNameForField}));"); } builder.AppendLine($"{indent}"); // Restore null default value if (overrideDefaultValue) { apiField.DefaultValue = null; } // Property if (!apiField.Optional && !apiField.Type.Nullable) { builder.AppendLine($"{indent}[Required]"); } if (apiField.Deprecation != null) { builder.AppendLine(apiField.Deprecation.ToCSharpDeprecation()); } builder.AppendLine($"{indent}[JsonPropertyName(\"{apiField.Name}\")]"); if (apiField.Type is ApiFieldType.Primitive apiFieldTypePrimitive) { var csharpType = apiFieldTypePrimitive.ToCSharpPrimitiveType(); if (csharpType.JsonConverter != null) { builder.AppendLine($"{indent}[JsonConverter(typeof({csharpType.JsonConverter.Name}))]"); } } builder.Append($"{indent}public "); builder.Append(apiField.Type.ToCSharpType(_codeGenerationContext)); if (apiField.Type.Nullable) { builder.Append("?"); } builder.Append(" "); builder.AppendLine($"{indent}{propertyNameForField}"); builder.AppendLine($"{indent}{{"); indent.Increment(); builder.AppendLine($"{indent}get => {backingFieldNameForField}.GetValue();"); builder.AppendLine($"{indent}set => {backingFieldNameForField}.SetValue(value);"); indent.Decrement(); builder.AppendLine($"{indent}}}"); return(builder.ToString()); }