public IEnumerable <TdsToken> GetResponseStream() { FormatToken format = null; while (true) { if (!ResponseAtEnd) { TdsToken token = _tokenBuilder.ReadToken(_res, Encoder, format); if (_tokenHandlers.TryGetValue(token.GetType(), out var handler)) { handler(token); } if (token is FormatToken) { format = (FormatToken)token; } ResponseAtEnd = token.IsEndOfResponse(); yield return(token); } else { yield break; } } }
private void SetPalette(FormatToken token, ConsolePalette palette, bool colorize) { if (colorize && token is PropertyToken) { if (palette.ArgumentBackground != Constants.DefaultConsoleColor) { _console.BackgroundColor = palette.ArgumentBackground; } if (palette.ArgumentForeground != Constants.DefaultConsoleColor) { _console.ForegroundColor = palette.ArgumentForeground; } } else { if (palette.Background != Constants.DefaultConsoleColor) { _console.BackgroundColor = palette.Background; } if (palette.Foreground != Constants.DefaultConsoleColor) { _console.ForegroundColor = palette.Foreground; } } }
public TdsToken ReadToken(TdsResponseStream stream, Encoding encoder, FormatToken lastFormat) { var tokenType = (TokenType)stream.Read(); TdsToken token = null; TokenDescriptor desc; if (_tokenDescriptors.TryGetValue(tokenType, out desc)) { if (desc.Builder == null) { token = CreateNotImplementedToken(desc, stream); } else { //_logger?.LogTrace($"Building token of type {tokenType}"); token = desc.Builder(desc, stream, encoder, lastFormat); _logger?.LogTrace(token.ToString()); } } else { _logger?.LogError($"Unknown token of type {tokenType}"); throw new Exception($"Unknown token of type {tokenType}"); } return(token); }
public string StandardFormat_With_StandardLocaleDefinition(FormatToken formatToken, string cultureName) { // Arrange CultureInfo culture = new CultureInfo(cultureName); // Act string result = MomentFormatter.Format(DateTime, formatToken, culture); // Assert return(result); }
public static int GetWidth(this FormatToken token) { switch (token) { case (FormatToken.Space): return(4); default: return(0); } }
private void SetPalette(FormatToken token, ConsolePalette palette) { if (token is PropertyToken) { _console.BackgroundColor = palette.ArgumentBackground; _console.ForegroundColor = palette.ArgumentForeground; } else { _console.BackgroundColor = palette.Background; _console.ForegroundColor = palette.Foreground; } }
private void SetPalette(FormatToken token, ConsolePalette palette) { var property = token as PropertyToken; if (property != null) { _console.BackgroundColor = palette.ArgumentBackground; _console.ForegroundColor = palette.ArgumentForeground; } else { _console.BackgroundColor = palette.Background; _console.ForegroundColor = palette.Foreground; } }
private string GetColorEscapeCode(FormatToken token, ConsolePalette palette) { if (token is PropertyToken) { var result = _ansiBackgroundLookup[palette.ArgumentBackground]; result += _ansiLookup[palette.ArgumentForeground]; return(result); } else { var result = _ansiBackgroundLookup[palette.Background]; result += _ansiLookup[palette.Foreground]; return(result); } }
public async Task <IActionResult> LogIn([FromForm] LoginUsers loginUsers) { if (await _repositoryLogin.LoginUser(loginUsers) == true) { string token = await _repositoryAuthenticationService.Authenticate(loginUsers); var formattedToken = FormatToken.FormattedToken(token); return(Ok(formattedToken)); } else { string token = await _repositoryAuthenticationService.Authenticate(loginUsers); return(NotFound(token)); } }
public void Format(FormatToken format) { switch (format) { case (FormatToken.Bold): Bold = !Bold; break; case (FormatToken.Underline): Underline = !Underline; break; case (FormatToken.Subscript): ScriptOffset += 8; break; case (FormatToken.Superscript): ScriptOffset -= 8; break; } }
private List <Tuple <FormatToken, List <DataToken>, DoneToken> > InitResultSets(IEnumerable <TdsToken> tokens) { var r = new List <Tuple <FormatToken, List <DataToken>, DoneToken> >(); FormatToken fmt = null; List <DataToken> rows = null; foreach (var t in tokens) { if (t is FormatToken) { var newFormat = (FormatToken)t; if (t.TokenType == TokenType.TDS_ROWFMT || t.TokenType == TokenType.TDS_ROWFMT2) { fmt = newFormat; rows = new List <DataToken>(); } } else if (t is DataToken && fmt != null) { var dataToken = (DataToken)t; if (dataToken.TokenType == TokenType.TDS_ROW) { rows.Add(dataToken); } } else if (t is DoneToken) { if (fmt != null) { r.Add(new Tuple <FormatToken, List <DataToken>, DoneToken>(fmt, rows, (DoneToken)t)); fmt = null; rows = null; } } } return(r); }
private TdsToken CreateLoginAck(TokenDescriptor tokenDesc, TdsResponseStream stream, Encoding encoder, FormatToken lastFormat) { int len = stream.ReadShort(); int status = stream.Read(); var version = stream.ReadBytes(4); int nameLen = stream.Read(); var name = stream.ReadString(nameLen); var progVersion = stream.ReadBytes(4); return(new LoginAckToken(tokenDesc.TokenType) { Succeed = status == 5, Fail = status == 6, Negotiate = status == 7, TdsVersion = $"{version[0]}.{version[1]}.{version[2]}.{version[3]}", ServerProgram = name, ServerVersion = $"{progVersion[0]}.{progVersion[1]}.{progVersion[2]}.{progVersion[3]}", }); }
internal static string Format(DateTime dateTime, FormatToken formatToken, CultureInfo culture) { return(Format(dateTime, formatToken.ToString(), culture)); }
private CharSequence transform(FormatToken token, object argument) { this.formatToken = token; this.arg = argument; // There are only two format specifiers that matter: "%d" and "%s". // Nothing else is common in the wild. We fast-path these two to // avoid the heavyweight machinery needed to cope with flags, width, // and precision. if (token.isDefault()) { switch (token.getConversionType()) { case 's': { if (arg == null) { return(CharSequenceProxy.Wrap("null")); } else { if (!(arg is java.util.Formattable)) { return(CharSequenceProxy.Wrap(arg.ToString())); } } break; } case 'd': { if (_out is StringBuilder) { if ((arg is int) || (arg is short) || (arg is byte) || (arg is long)) { ((StringBuilder)_out).append(arg.ToString()); return(null); } } if (arg is int || arg is long || arg is short || arg is byte) { return(CharSequenceProxy.Wrap(arg.ToString())); } } break; } } formatToken.checkFlags(arg); CharSequence result_1; switch (token.getConversionType()) { case 'B': case 'b': { result_1 = transformFromBoolean(); break; } case 'H': case 'h': { result_1 = transformFromHashCode(); break; } case 'S': case 's': { result_1 = transformFromString(); break; } case 'C': case 'c': { result_1 = transformFromCharacter(); break; } case 'd': case 'o': case 'x': case 'X': { result_1 = transformFromInteger(); break; } case 'A': case 'a': case 'E': case 'e': case 'f': case 'G': case 'g': { result_1 = transformFromFloat(); break; } case '%': { result_1 = transformFromPercent(); break; } case 'n': { result_1 = CharSequenceProxy.Wrap(Environment.NewLine); break; } case 't': case 'T': { result_1 = transformFromDateTime(); break; } default: { throw token.unknownFormatConversionException(); } } if (System.Char.IsUpper(token.getConversionType())) { if (result_1 != null) { result_1 = CharSequenceProxy.Wrap(result_1.ToString().ToUpper(_locale)); } } return(result_1); }
private TdsToken CreateReturnStatus(TokenDescriptor tokenDesc, TdsResponseStream stream, Encoding encoder, FormatToken lastFormat) { int value = stream.ReadInt(); return(new ReturnStatusToken(tokenDesc.TokenType) { Value = value, }); }
private CharSequence transform (FormatToken token, object argument) { this.formatToken = token; this.arg = argument; // There are only two format specifiers that matter: "%d" and "%s". // Nothing else is common in the wild. We fast-path these two to // avoid the heavyweight machinery needed to cope with flags, width, // and precision. if (token.isDefault ()) { switch (token.getConversionType ()) { case 's': { if (arg == null) { return CharSequenceProxy.Wrap ("null"); } else { if (!(arg is java.util.Formattable)) { return CharSequenceProxy.Wrap (arg.ToString ()); } } break; } case 'd': { if (_out is StringBuilder) { if ((arg is int) || (arg is short) || (arg is byte) || (arg is long)) { ((StringBuilder)_out).append (arg.ToString ()); return null; } } if (arg is int || arg is long || arg is short || arg is byte) { return CharSequenceProxy.Wrap (arg.ToString ()); } } break; } } formatToken.checkFlags (arg); CharSequence result_1; switch (token.getConversionType ()) { case 'B': case 'b': { result_1 = transformFromBoolean (); break; } case 'H': case 'h': { result_1 = transformFromHashCode (); break; } case 'S': case 's': { result_1 = transformFromString (); break; } case 'C': case 'c': { result_1 = transformFromCharacter (); break; } case 'd': case 'o': case 'x': case 'X': { result_1 = transformFromInteger (); break; } case 'A': case 'a': case 'E': case 'e': case 'f': case 'G': case 'g': { result_1 = transformFromFloat (); break; } case '%': { result_1 = transformFromPercent (); break; } case 'n': { result_1 = CharSequenceProxy.Wrap (Environment.NewLine); break; } case 't': case 'T': { result_1 = transformFromDateTime (); break; } default: { throw token.unknownFormatConversionException (); } } if (System.Char.IsUpper (token.getConversionType ())) { if (result_1 != null) { result_1 = CharSequenceProxy.Wrap (result_1.ToString ().ToUpper (_locale)); } } return result_1; }
private TdsToken CreateData(TokenDescriptor tokenDesc, TdsResponseStream stream, Encoding encoder, FormatToken lastFormat) { if (lastFormat == null) { _logger?.LogError($"Format for {tokenDesc.TokenType} not found"); throw new Exception($"Format for {tokenDesc.TokenType} not found"); } var data = new List <object>(); foreach (var f in lastFormat.Formats) { data.Add(TypeReader.ReadData(f, stream, encoder)); } return(new DataToken(tokenDesc.TokenType) { Data = data, }); }
internal HeaderInfo GenerateHeaderInfo(PSObject input, TableControlBody tableBody, OutGridViewCommand parentCmdlet) { HeaderInfo headerInfo = new HeaderInfo(); // This verification is needed because the database returns "LastWriteTime" value for file system objects // as strings and it is used to detect this situation and use the actual field value. bool fileSystemObject = typeof(FileSystemInfo).IsInstanceOfType(input.BaseObject); if (tableBody != null) // If the tableBody is null, the TableControlBody info was not put into the database. { // Generate HeaderInfo from the type information database. List <TableRowItemDefinition> activeRowItemDefinitionList = GetActiveTableRowDefinition(tableBody, input); int col = 0; foreach (TableRowItemDefinition rowItem in activeRowItemDefinitionList) { ColumnInfo columnInfo = null; string displayName = null; TableColumnHeaderDefinition colHeader = null; // Retrieve a matching TableColumnHeaderDefinition if (col < tableBody.header.columnHeaderDefinitionList.Count) { colHeader = tableBody.header.columnHeaderDefinitionList[col]; } if (colHeader != null && colHeader.label != null) { displayName = _typeInfoDatabase.displayResourceManagerCache.GetTextTokenString(colHeader.label); } FormatToken token = null; if (rowItem.formatTokenList.Count > 0) { token = rowItem.formatTokenList[0]; } if (token != null) { FieldPropertyToken fpt = token as FieldPropertyToken; if (fpt != null) { if (displayName == null) { // Database does not provide a label(DisplayName) for the current property, use the expression value instead. displayName = fpt.expression.expressionValue; } if (fpt.expression.isScriptBlock) { PSPropertyExpression ex = _expressionFactory.CreateFromExpressionToken(fpt.expression); // Using the displayName as a propertyName for a stale PSObject. const string LastWriteTimePropertyName = "LastWriteTime"; // For FileSystem objects "LastWriteTime" property value should be used although the database indicates that a script should be executed to get the value. if (fileSystemObject && displayName.Equals(LastWriteTimePropertyName, StringComparison.OrdinalIgnoreCase)) { columnInfo = new OriginalColumnInfo(displayName, displayName, LastWriteTimePropertyName, parentCmdlet); } else { columnInfo = new ExpressionColumnInfo(displayName, displayName, ex); } } else { columnInfo = new OriginalColumnInfo(fpt.expression.expressionValue, displayName, fpt.expression.expressionValue, parentCmdlet); } } else { TextToken tt = token as TextToken; if (tt != null) { displayName = _typeInfoDatabase.displayResourceManagerCache.GetTextTokenString(tt); columnInfo = new OriginalColumnInfo(tt.text, displayName, tt.text, parentCmdlet); } } } if (columnInfo != null) { headerInfo.AddColumn(columnInfo); } col++; } } return(headerInfo); }
// Token: 0x060005A3 RID: 1443 RVA: 0x00011994 File Offset: 0x0000FB94 private void Format(FormatTokenCollection tokens, IFormatProvider formatProvider, object[] arguments) { for (int i = 0; i < tokens.Count; i++) { FormatToken formatToken = tokens[i]; LiteralFormatToken literalFormatToken = formatToken as LiteralFormatToken; if (literalFormatToken != null) { this.stringBuilder.Append(literalFormatToken.Literal); } else { FormattedFormatToken formattedFormatToken = formatToken as FormattedFormatToken; if (formattedFormatToken != null) { IFormattable formattable = arguments[formattedFormatToken.ArgumentNumber] as IFormattable; string text; if (formattable != null) { text = formattable.ToString(formattedFormatToken.FormatString, formatProvider); } else if (arguments[formattedFormatToken.ArgumentNumber] != null) { text = arguments[formattedFormatToken.ArgumentNumber].ToString(); } else { text = ""; } if (formattedFormatToken.Spacing > 0 && text.Length < formattedFormatToken.Spacing) { if (formattedFormatToken.Alignment == FormattedFormatToken.StringAlignment.LeftAligned) { this.stringBuilder.Append(text); this.stringBuilder.Append(' ', formattedFormatToken.Spacing - text.Length); } else { this.stringBuilder.Append(' ', formattedFormatToken.Spacing - text.Length); this.stringBuilder.Append(text); } } else { this.stringBuilder.Append(text); } } else { ConditionalFormatToken conditionalFormatToken = formatToken as ConditionalFormatToken; if (conditionalFormatToken != null) { bool flag = true; if (arguments[conditionalFormatToken.ArgumentNumber] == null) { flag = false; } else { bool?flag2 = arguments[conditionalFormatToken.ArgumentNumber] as bool?; if (flag2 != null) { flag = flag2.Value; } } if (conditionalFormatToken.Inverted) { flag = !flag; } this.Format(flag ? conditionalFormatToken.TrueTokens : conditionalFormatToken.FalseTokens, formatProvider, arguments); } } } } }
private TdsToken CreateCapabiltiy(TokenDescriptor tokenDesc, TdsResponseStream stream, Encoding encoder, FormatToken lastFormat) { int len = stream.ReadShort(); if (stream.Read() != 1) { throw new Exception("TDS_CAPABILITY: expected request string"); } int capReqLen = stream.Read(); if (capReqLen != 11 && capReqLen != 0) { throw new Exception("TDS_CAPABILITY: byte count not 11"); } byte[] capRequest = new byte[11]; if (capReqLen != 0) { stream.Read(capRequest, 0, 11); } if (stream.Read() != 2) { throw new Exception("TDS_CAPABILITY: expected response string"); } int capResLen = stream.Read(); if (capResLen != 10 && capResLen != 0) { throw new Exception("TDS_CAPABILITY: byte count not 10"); } byte[] capResponse = new byte[10]; if (capResLen != 0) { stream.Read(capResponse, 0, 10); } return(new CapabiltiyToken(tokenDesc.TokenType, capRequest, capResponse)); }
private TdsToken CreateDone(TokenDescriptor tokenDesc, TdsResponseStream stream, Encoding encoder, FormatToken lastFormat) { int status = stream.ReadShort(); int tranState = stream.ReadShort(); int count = stream.ReadInt(); return(new DoneToken(tokenDesc.TokenType) { More = (status & 1) != 0, Error = (status & 2) != 0, InTransaction = (status & 4) != 0, Proc = (status & 8) != 0, Count = (status & 16) != 0, AttentionAck = (status & 32) != 0, //Event = (status & 64) != 0, TransactionState = (DoneToken.TransactionStatus)tranState, RowCount = (status & 16) != 0 ? count : (int?)null, }); }
private TdsToken CreateTextMessage(TokenDescriptor tokenDesc, TdsResponseStream stream, Encoding encoder, FormatToken lastFormat) { int len = stream.ReadShort(); int msgNumber = stream.ReadInt(); int state = stream.Read(); int severity = stream.Read(); int sqlStatusLen = stream.Read(); var sqlStatus = stream.ReadBytes(sqlStatusLen); int status = stream.Read(); int tranState = stream.ReadShort(); // discarded int msgLen = stream.ReadShort(); var msg = stream.ReadString(msgLen); int srvNameLen = stream.Read(); var serverName = stream.ReadString(srvNameLen); int procNameLen = stream.Read(); var procName = stream.ReadString(procNameLen); int lineNumber = stream.ReadShort(); return(new TextMessageToken(tokenDesc.TokenType) { MessageNumber = msgNumber, State = state, Severity = severity, ParamsFollows = status == 1, Message = msg, ServerName = serverName, ProcName = procName, LineNumber = lineNumber, }); }
private TdsToken CreateEnvChange(TokenDescriptor tokenDesc, TdsResponseStream stream, Encoding encoder, FormatToken lastFormat) { int len = stream.ReadShort(); int read = 0; var changes = new List <EnvChangeToken.Change>(); while (read < len) { var change = new EnvChangeToken.Change(); change.Type = (EnvChangeToken.EnvType)stream.Read(); int newValLen = stream.Read(); change.NewValue = stream.ReadString(newValLen); int oldValLen = stream.Read(); change.OldValue = stream.ReadString(oldValLen); read += 3 + newValLen + oldValLen; changes.Add(change); } return(new EnvChangeToken(tokenDesc.TokenType) { Changes = changes }); }
private TdsToken CreateFormat(TokenDescriptor tokenDesc, TdsResponseStream stream, Encoding encoder, FormatToken lastFormat) { int len; if (tokenDesc.Len == TokenLength.FourByteLen) { len = stream.ReadInt(); } else { len = stream.ReadShort(); } int numFormats = stream.ReadShort(); var formats = new List <FormatToken.Format>(); for (int i = 0; i < numFormats; i++) { var f = new FormatToken.Format { Params = tokenDesc.TokenType == TokenType.TDS_PARAMFMT || tokenDesc.TokenType == TokenType.TDS_PARAMFMT2, }; int nameLen = stream.Read(); f.Name = stream.ReadString(nameLen); if (tokenDesc.TokenType == TokenType.TDS_ROWFMT2) { int catalogNameLen = stream.Read(); f.CatalogName = stream.ReadString(catalogNameLen); int schemaNameLen = stream.Read(); f.SchemaName = stream.ReadString(schemaNameLen); int tableNameLen = stream.Read(); f.TableName = stream.ReadString(tableNameLen); int columnNameLen = stream.Read(); f.ColumnName = stream.ReadString(columnNameLen); } if (tokenDesc.Len == TokenLength.FourByteLen) { f.Status = stream.ReadInt(); } else { f.Status = stream.Read(); } f.UserType = (UserDataType)stream.ReadInt(); f.Type = (TdsType)stream.Read(); TypeReader.ReadFormat(f, stream); formats.Add(f); } return(new FormatToken(tokenDesc.TokenType) { Formats = formats, }); }
internal HeaderInfo GenerateHeaderInfo(PSObject input, TableControlBody tableBody, OutGridViewCommand parentCmdlet) { HeaderInfo info = new HeaderInfo(); bool flag = typeof(FileSystemInfo).IsInstanceOfType(input.BaseObject); if (tableBody != null) { List <TableRowItemDefinition> activeTableRowDefinition = this.GetActiveTableRowDefinition(tableBody, input); int num = 0; foreach (TableRowItemDefinition definition in activeTableRowDefinition) { Microsoft.PowerShell.Commands.ColumnInfo col = null; string staleObjectPropertyName = null; TableColumnHeaderDefinition definition2 = null; if (tableBody.header.columnHeaderDefinitionList.Count >= (num - 1)) { definition2 = tableBody.header.columnHeaderDefinitionList[num]; } if ((definition2 != null) && (definition2.label != null)) { staleObjectPropertyName = this.typeInfoDatabase.displayResourceManagerCache.GetTextTokenString(definition2.label); } FormatToken token = null; if (definition.formatTokenList.Count > 0) { token = definition.formatTokenList[0]; } if (token != null) { FieldPropertyToken token2 = token as FieldPropertyToken; if (token2 != null) { if (staleObjectPropertyName == null) { staleObjectPropertyName = token2.expression.expressionValue; } if (token2.expression.isScriptBlock) { MshExpression expression = this.expressionFactory.CreateFromExpressionToken(token2.expression); if (flag && staleObjectPropertyName.Equals("LastWriteTime", StringComparison.OrdinalIgnoreCase)) { col = new OriginalColumnInfo(staleObjectPropertyName, staleObjectPropertyName, "LastWriteTime", parentCmdlet); } else { col = new ExpressionColumnInfo(staleObjectPropertyName, staleObjectPropertyName, expression); } } else { col = new OriginalColumnInfo(token2.expression.expressionValue, staleObjectPropertyName, token2.expression.expressionValue, parentCmdlet); } } else { TextToken tt = token as TextToken; if (tt != null) { staleObjectPropertyName = this.typeInfoDatabase.displayResourceManagerCache.GetTextTokenString(tt); col = new OriginalColumnInfo(tt.text, staleObjectPropertyName, tt.text, parentCmdlet); } } } if (col != null) { info.AddColumn(col); } num++; } } return(info); }
private TdsToken CreateControl(TokenDescriptor tokenDesc, TdsResponseStream stream, Encoding encoder, FormatToken lastFormat) { int len = stream.ReadShort(); int read = 0; var formats = new List <string>(); while (read < len) { int formatLen = stream.Read(); var format = stream.ReadString(formatLen); read += 1 + formatLen; formats.Add(format); } return(new ControlToken(tokenDesc.TokenType) { Formats = formats }); }
internal static CustomItemBase Create(FormatToken token) { if (token is NewLineToken) { return(new CustomItemNewline()); } var textToken = token as TextToken; if (textToken != null) { return(new CustomItemText { Text = textToken.text }); } var frameToken = token as FrameToken; if (frameToken != null) { var frame = new CustomItemFrame { RightIndent = (uint)frameToken.frameInfoDefinition.rightIndentation, LeftIndent = (uint)frameToken.frameInfoDefinition.leftIndentation }; var firstLine = frameToken.frameInfoDefinition.firstLine; if (firstLine > 0) { frame.FirstLineIndent = (uint)firstLine; } else if (firstLine < 0) { frame.FirstLineHanging = (uint)-firstLine; } foreach (var frameItemToken in frameToken.itemDefinition.formatTokenList) { frame.CustomItems.Add(CustomItemBase.Create(frameItemToken)); } return(frame); } var cpt = token as CompoundPropertyToken; if (cpt != null) { var cie = new CustomItemExpression { EnumerateCollection = cpt.enumerateCollection }; if (cpt.conditionToken != null) { cie.ItemSelectionCondition = new DisplayEntry(cpt.conditionToken); } if (cpt.expression.expressionValue != null) { cie.Expression = new DisplayEntry(cpt.expression); } if (cpt.control != null) { cie.CustomControl = new CustomControl((ComplexControlBody)cpt.control, null); } return(cie); } var fpt = token as FieldPropertyToken; if (fpt != null) { } Diagnostics.Assert(false, "Unexpected formatting token kind"); return(null); }
/// <summary> /// @see also: https://github.com/Trass3r/AsmHighlighter/blob/master/AsmHighlighter/AsmHighlighterFormatHelper.cs /// @see also: https://github.com/samizzo/nshader/blob/master/NShaderVS/NShaderFormatHelper.cs /// https://msdn.microsoft.com/en-us/library/bb164633.aspx /// </summary> /// <param name="pBuffer"></param> /// <param name="span"></param> /// <param name="tabSize"></param> /// <returns></returns> internal static List <EditSpan> ReformatCode(IVsTextLines pBuffer, int[] indents, bool[] comments, bool[] unFormat, TextSpan span) { Scanner lex = new Scanner(); List <EditSpan> changeList = new List <EditSpan>(); string line = ""; for (int i = span.iStartLine; i <= span.iEndLine; ++i) { if (unFormat[i] || comments[i]) { continue; } bool binaryOp = false; int startIndex = 0; int endIndex = 0; pBuffer.GetLengthOfLine(i, out endIndex); pBuffer.GetLineText(i, startIndex, i, endIndex, out line); //rules of formatting //rule 1: insert space before and after binary operator if there not any //rule 2: insert space after comma, semicolon if there not any //rule 3: indentation increase inside block //rule 4: multiple spaces replaced by a single space //rule 5: no spaces after left parentheses("(") and before right parentheses(")") //rule 6: no spaces between identifier and left parentheses("(") //rule 7: no spaces before and after colon ":" int state = 0, start = 0, end = 0; int firstSpaceEnd = -1; lex.SetSource(line, 0); int token = lex.GetNext(ref state, out start, out end); if ((Tokens)token == Tokens.LEX_WHITE) // skip spaces at front of the line { firstSpaceEnd = end; token = lex.GetNext(ref state, out start, out end); } // set indentation if (!(firstSpaceEnd == -1 && indents[i] == 0)) { string indentation = ""; for (int j = 0; j < indents[i]; ++j) { indentation = "\t" + indentation; } TextSpan firstSpaceSpan = new TextSpan(); firstSpaceSpan.iStartLine = i; firstSpaceSpan.iEndLine = i; firstSpaceSpan.iStartIndex = 0; firstSpaceSpan.iEndIndex = firstSpaceEnd + 1; changeList.Add(new EditSpan(firstSpaceSpan, indentation)); } FormatToken currentToken = new FormatToken((int)token, start, end); FormatToken lastToken = new FormatToken((int)Tokens.EOF, start - 1, start - 1); while (currentToken.token != (int)Tokens.EOF) { token = lex.GetNext(ref state, out start, out end); // fix issue of last unknow space if (start > end) { break; } FormatToken nextToken = new FormatToken((int)token, start, end); if (currentToken.token == (int)Tokens.LEX_WHITE && nextToken.token != (int)Tokens.LEX_COMMENT) // spaces, leave the space before comment { string SpaceorEmpty = " "; if (nextToken.token == (int)Tokens.RPAREN || // if meet right paren, remove spaces (nextToken.token == (int)Tokens.LPAREN && // rule 6 lastToken.token != (int)Tokens.KWFUNCTION) || nextToken.token == (int)Tokens.LBRACKET || nextToken.token == (int)Tokens.COLON || lastToken.token == (int)Tokens.COLON) { SpaceorEmpty = ""; } TextSpan spaceEdit = new TextSpan(); spaceEdit.iStartLine = i; spaceEdit.iEndLine = i; spaceEdit.iStartIndex = currentToken.startIndex; spaceEdit.iEndIndex = currentToken.endIndex + 1; changeList.Add(new EditSpan(spaceEdit, SpaceorEmpty)); } else if (currentToken.token == (int)Tokens.COMMA || currentToken.token == (int)Tokens.SEMICOLON) // comma, semicolon { if (nextToken.token != (int)Tokens.LEX_WHITE && nextToken.token != (int)Tokens.EOF) { string space = " "; TextSpan spaceEdit = new TextSpan(); spaceEdit.iStartLine = i; spaceEdit.iEndLine = i; spaceEdit.iStartIndex = currentToken.endIndex + 1; spaceEdit.iEndIndex = currentToken.endIndex + 1; changeList.Add(new EditSpan(spaceEdit, space)); } } else if (currentToken.token == (int)Tokens.PLUS || //binary operators currentToken.token == (int)Tokens.ASTERISK || currentToken.token == (int)Tokens.SLASH || currentToken.token == (int)Tokens.EQUAL) { if (lastToken.token != (int)Tokens.LEX_WHITE && lastToken.token != (int)Tokens.EOF) { string space = " "; TextSpan spaceEdit = new TextSpan(); spaceEdit.iStartLine = i; spaceEdit.iEndLine = i; spaceEdit.iStartIndex = currentToken.startIndex; spaceEdit.iEndIndex = currentToken.startIndex; changeList.Add(new EditSpan(spaceEdit, space)); } if (nextToken.token != (int)Tokens.LEX_WHITE && nextToken.token != (int)Tokens.EOF) { string space = " "; TextSpan spaceEdit = new TextSpan(); spaceEdit.iStartLine = i; spaceEdit.iEndLine = i; spaceEdit.iStartIndex = currentToken.endIndex + 1; spaceEdit.iEndIndex = currentToken.endIndex + 1; changeList.Add(new EditSpan(spaceEdit, space)); } } else if ((currentToken.token == (int)Tokens.MINUS) && //binary operators binaryOp) { if (lastToken.token != (int)Tokens.LEX_WHITE && lastToken.token != (int)Tokens.EOF) { string space = " "; TextSpan spaceEdit = new TextSpan(); spaceEdit.iStartLine = i; spaceEdit.iEndLine = i; spaceEdit.iStartIndex = currentToken.startIndex; spaceEdit.iEndIndex = currentToken.startIndex; changeList.Add(new EditSpan(spaceEdit, space)); } if (nextToken.token != (int)Tokens.LEX_WHITE && nextToken.token != (int)Tokens.EOF) { string space = " "; TextSpan spaceEdit = new TextSpan(); spaceEdit.iStartLine = i; spaceEdit.iEndLine = i; spaceEdit.iStartIndex = currentToken.endIndex + 1; spaceEdit.iEndIndex = currentToken.endIndex + 1; changeList.Add(new EditSpan(spaceEdit, space)); } binaryOp = false; } else if (currentToken.token == (int)Tokens.NUMBER) { if (nextToken.token == (int)Tokens.LEX_WHITE) { // get new nextToken token = lex.GetNext(ref state, out start, out end); if (start > end) { break; } if (token == (int)Tokens.PLUS || token == (int)Tokens.MINUS) { binaryOp = true; } //nextToken = new FormatToken(token, start, end); } else if (nextToken.token == (int)Tokens.PLUS || nextToken.token == (int)Tokens.MINUS) { binaryOp = true; } } else if (currentToken.token == (int)Tokens.LPAREN && nextToken.token == (int)Tokens.LEX_WHITE) { string empty = ""; TextSpan emptyEdit = new TextSpan(); emptyEdit.iStartLine = i; emptyEdit.iEndLine = i; emptyEdit.iStartIndex = nextToken.startIndex; emptyEdit.iEndIndex = nextToken.endIndex + 1; changeList.Add(new EditSpan(emptyEdit, empty)); // get new nextToken token = lex.GetNext(ref state, out start, out end); // fix issue of last unknow space if (start > end) { break; } nextToken = new FormatToken(token, start, end); } lastToken = currentToken; currentToken = nextToken; } } return(changeList); }