clang 22.0.0git
Format.h File Reference

Various functions to configurably format source code. More...

#include "clang/Basic/LangOptions.h"
#include "clang/Tooling/Core/Replacement.h"
#include "clang/Tooling/Inclusions/IncludeStyle.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/Support/Regex.h"
#include "llvm/Support/SourceMgr.h"
#include <optional>
#include <system_error>

Go to the source code of this file.

Classes

class  clang::format::ParseErrorCategory
struct  clang::KeepEmptyLinesStyle
 Options regarding which empty lines are kept. More...
struct  clang::NumericLiteralCaseStyle
 Separate control for each numeric literal component. More...
struct  clang::RawStringFormat
 See documentation of RawStringFormats. More...
struct  clang::SortIncludesOptions
 Includes sorting options. More...
struct  clang::SpaceBeforeParensCustom
 Precise control over the spacing before parentheses. More...
struct  clang::SpacesInLineComment
 If true, spaces may be inserted into C style casts. This option is deprecated. See InCStyleCasts of SpacesInParensOptions. More...
struct  clang::SpacesInParensCustom
 Precise control over the spacing in parentheses. More...
struct  clang::FormatStyleSet
struct  FormattingAttemptStatus
 Represents the status of a formatting attempt. More...
struct  std::is_error_code_enum< clang::format::ParseError >

Namespaces

namespace  llvm
 Diagnostic wrappers for TextAPI types for error reporting.
namespace  llvm::vfs
namespace  clang
 The JSON file list parser is used to communicate input to InstallAPI.
namespace  clang::format

Enumerations

enum class  clang::format::ParseError {
  clang::format::Success = 0 , clang::format::Error , clang::format::Unsuitable , clang::format::BinPackTrailingCommaConflict ,
  clang::format::InvalidQualifierSpecified , clang::format::DuplicateQualifierSpecified , clang::format::MissingQualifierType , clang::format::MissingQualifierOrder
}
enum  clang::JavaScriptQuoteStyle : int8_t { clang::JSQS_Leave , clang::JSQS_Single , clang::JSQS_Double }
 Quotation styles for JavaScript strings. Does not affect template strings. More...
enum  clang::LambdaBodyIndentationKind : int8_t { clang::LBI_Signature , clang::LBI_OuterScope }
 Indentation logic for lambda bodies. More...
enum  clang::LanguageKind : int8_t {
  clang::LK_None , clang::LK_C , clang::LK_Cpp , clang::LK_CSharp ,
  clang::LK_Java , clang::LK_JavaScript , clang::LK_Json , clang::LK_ObjC ,
  clang::LK_Proto , clang::LK_TableGen , clang::LK_TextProto , clang::LK_Verilog
}
 Supported languages. More...
enum  clang::LineEndingStyle : int8_t { clang::LE_LF , clang::LE_CRLF , clang::LE_DeriveLF , clang::LE_DeriveCRLF }
 Line ending style. More...
enum  clang::NamespaceIndentationKind : int8_t { clang::NI_None , clang::NI_Inner , clang::NI_All }
 Different ways to indent namespace contents. More...
enum  clang::NumericLiteralComponentStyle : int8_t { clang::NLCS_Leave , clang::NLCS_Upper , clang::NLCS_Lower }
 Control over each component in a numeric literal. More...
enum  clang::PackConstructorInitializersStyle : int8_t {
  clang::PCIS_Never , clang::PCIS_BinPack , clang::PCIS_CurrentLine , clang::PCIS_NextLine ,
  clang::PCIS_NextLineOnly
}
 Different ways to try to fit all constructor initializers on a line. More...
enum  clang::PointerAlignmentStyle : int8_t { clang::PAS_Left , clang::PAS_Right , clang::PAS_Middle }
 The &, && and * alignment style. More...
enum  clang::QualifierAlignmentStyle : int8_t { clang::QAS_Leave , clang::QAS_Left , clang::QAS_Right , clang::QAS_Custom }
 Different specifiers and qualifiers alignment styles. More...
enum  clang::ReferenceAlignmentStyle : int8_t { clang::RAS_Pointer , clang::RAS_Left , clang::RAS_Right , clang::RAS_Middle }
 The & and && alignment style. More...
enum  clang::ReflowCommentsStyle : int8_t { clang::RCS_Never , clang::RCS_IndentOnly , clang::RCS_Always }
 Types of comment reflow style. More...
enum  clang::RemoveParenthesesStyle : int8_t { clang::RPS_Leave , clang::RPS_MultipleParentheses , clang::RPS_ReturnStatement }
 Types of redundant parentheses to remove. More...
enum  clang::RequiresClausePositionStyle : int8_t {
  clang::RCPS_OwnLine , clang::RCPS_OwnLineWithBrace , clang::RCPS_WithPreceding , clang::RCPS_WithFollowing ,
  clang::RCPS_SingleLine
}
 The possible positions for the requires clause. The IndentRequires option is only used if the requires is put on the start of a line. More...
enum  clang::RequiresExpressionIndentationKind : int8_t { clang::REI_OuterScope , clang::REI_Keyword }
 Indentation logic for requires expression bodies. More...
enum  clang::SeparateDefinitionStyle : int8_t { clang::SDS_Leave , clang::SDS_Always , clang::SDS_Never }
 The style if definition blocks should be separated. More...
enum  clang::SortJavaStaticImportOptions : int8_t { clang::SJSIO_Before , clang::SJSIO_After }
 Position for Java Static imports. More...
enum  clang::SortUsingDeclarationsOptions : int8_t { clang::SUD_Never , clang::SUD_Lexicographic , clang::SUD_LexicographicNumeric }
 Using declaration sorting options. More...
enum  clang::SpaceAroundPointerQualifiersStyle : int8_t { clang::SAPQ_Default , clang::SAPQ_Before , clang::SAPQ_After , clang::SAPQ_Both }
 Different ways to put a space before opening parentheses. More...
enum  clang::SpaceBeforeParensStyle : int8_t {
  clang::SBPO_Never , clang::SBPO_ControlStatements , clang::SBPO_ControlStatementsExceptControlMacros , clang::SBPO_NonEmptyParentheses ,
  clang::SBPO_Always , clang::SBPO_Custom
}
 Different ways to put a space before opening parentheses. More...
enum  clang::SpaceInEmptyBracesStyle : int8_t { clang::SIEB_Always , clang::SIEB_Block , clang::SIEB_Never }
 This option is deprecated. See Block of SpaceInEmptyBraces. More...
enum  clang::SpacesInAnglesStyle : int8_t { clang::SIAS_Never , clang::SIAS_Always , clang::SIAS_Leave }
 Styles for adding spacing after < and before > in template argument lists. More...
enum  clang::SpacesInParensStyle : int8_t { clang::SIPO_Never , clang::SIPO_Custom }
 Different ways to put a space before opening and closing parentheses. More...
enum  clang::LanguageStandard : int8_t {
  clang::LS_Cpp03 , clang::LS_Cpp11 , clang::LS_Cpp14 , clang::LS_Cpp17 ,
  clang::LS_Cpp20 , clang::LS_Latest , clang::LS_Auto
}
 Supported language standards for parsing and formatting C++ constructs. More...
enum  clang::DAGArgStyle : int8_t { clang::DAS_DontBreak , clang::DAS_BreakElements , clang::DAS_BreakAll }
 Different ways to control the format inside TableGen DAGArg. More...
enum  clang::UseTabStyle : int8_t {
  clang::UT_Never , clang::UT_ForIndentation , clang::UT_ForContinuationAndIndentation , clang::UT_AlignWithSpaces ,
  clang::UT_Always
}
 This option is deprecated. See LF and CRLF of LineEnding. More...
enum  clang::WrapNamespaceBodyWithEmptyLinesStyle : int8_t { clang::WNBWELS_Never , clang::WNBWELS_Always , clang::WNBWELS_Leave }
 Different styles for wrapping namespace body with empty lines. More...

Functions

const std::error_category & clang::format::getParseCategory ()
std::error_code clang::format::make_error_code (ParseError e)
bool clang::isCpp () const
bool clang::isCSharp () const
bool clang::isJson () const
bool clang::isJava () const
bool clang::isJavaScript () const
bool clang::isVerilog () const
bool clang::isTextProto () const
bool clang::isProto () const
bool clang::isTableGen () const
bool clang::operator== (const FormatStyle &R) const
std::optional< FormatStyle > clang::GetLanguageStyle (LanguageKind Language) const
static FormatStyleSet clang::BuildStyleSetFromConfiguration (const FormatStyle &MainStyle, const std::vector< FormatStyle > &ConfigurationStyles)
FormatStyle getLLVMStyle (FormatStyle::LanguageKind Language=FormatStyle::LK_Cpp)
 Returns a format style complying with the LLVM coding standards: http://llvm.org/docs/CodingStandards.html.
FormatStyle getGoogleStyle (FormatStyle::LanguageKind Language)
 Returns a format style complying with one of Google's style guides: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml. http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml. https://developers.google.com/protocol-buffers/docs/style.
FormatStyle getChromiumStyle (FormatStyle::LanguageKind Language)
 Returns a format style complying with Chromium's style guide: http://www.chromium.org/developers/coding-style.
FormatStyle getMozillaStyle ()
 Returns a format style complying with Mozilla's style guide: https://firefox-source-docs.mozilla.org/code-quality/coding-style/index.html.
FormatStyle getWebKitStyle ()
 Returns a format style complying with Webkit's style guide: http://www.webkit.org/coding/coding-style.html.
FormatStyle getGNUStyle ()
 Returns a format style complying with GNU Coding Standards: http://www.gnu.org/prep/standards/standards.html.
FormatStyle getMicrosoftStyle (FormatStyle::LanguageKind Language)
 Returns a format style complying with Microsoft style guide: https://docs.microsoft.com/en-us/visualstudio/ide/editorconfig-code-style-settings-reference?view=vs-2017.
FormatStyle getClangFormatStyle ()
FormatStyle getNoStyle ()
 Returns style indicating formatting should be not applied at all.
bool getPredefinedStyle (StringRef Name, FormatStyle::LanguageKind Language, FormatStyle *Style)
 Gets a predefined style for the specified language by name.
std::error_code parseConfiguration (llvm::MemoryBufferRef Config, FormatStyle *Style, bool AllowUnknownOptions=false, llvm::SourceMgr::DiagHandlerTy DiagHandler=nullptr, void *DiagHandlerCtx=nullptr, bool IsDotHFile=false)
 Parse configuration from YAML-formatted text.
std::error_code parseConfiguration (StringRef Config, FormatStyle *Style, bool AllowUnknownOptions=false, bool IsDotHFile=false)
 Like above but accepts an unnamed buffer.
std::string configurationAsText (const FormatStyle &Style)
 Gets configuration in a YAML string.
tooling::Replacements sortIncludes (const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName, unsigned *Cursor=nullptr)
 Returns the replacements necessary to sort all #include blocks that are affected by Ranges.
Expected< tooling::Replacements > formatReplacements (StringRef Code, const tooling::Replacements &Replaces, const FormatStyle &Style)
 Returns the replacements corresponding to applying and formatting Replaces on success; otheriwse, return an llvm::Error carrying llvm::StringError.
Expected< tooling::Replacements > cleanupAroundReplacements (StringRef Code, const tooling::Replacements &Replaces, const FormatStyle &Style)
 Returns the replacements corresponding to applying Replaces and cleaning up the code after that on success; otherwise, return an llvm::Error carrying llvm::StringError. This also supports inserting/deleting C++ #include directives:
tooling::Replacements reformat (const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>", FormattingAttemptStatus *Status=nullptr)
 Reformats the given Ranges in Code.
tooling::Replacements reformat (const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName, bool *IncompleteFormat)
 Same as above, except if IncompleteFormat is non-null, its value will be set to true if any of the affected ranges were not formatted due to a non-recoverable syntax error.
tooling::Replacements cleanup (const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>")
 Clean up any erroneous/redundant code in the given Ranges in Code.
tooling::Replacements fixNamespaceEndComments (const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>")
 Fix namespace end comments in the given Ranges in Code.
tooling::Replacements separateDefinitionBlocks (const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>")
 Inserts or removes empty lines separating definition blocks including classes, structs, functions, namespaces, and enums in the given Ranges in Code.
tooling::Replacements sortUsingDeclarations (const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>")
 Sort consecutive using declarations in the given Ranges in Code.
LangOptions getFormattingLangOpts (const FormatStyle &Style=getLLVMStyle())
 Returns the LangOpts that the formatter expects you to set.
Expected< FormatStyle > getStyle (StringRef StyleName, StringRef FileName, StringRef FallbackStyle, StringRef Code="", llvm::vfs::FileSystem *FS=nullptr, bool AllowUnknownOptions=false, llvm::SourceMgr::DiagHandlerTy DiagHandler=nullptr)
 Construct a FormatStyle based on StyleName.
FormatStyle::LanguageKind guessLanguage (StringRef FileName, StringRef Code)
StringRef getLanguageName (FormatStyle::LanguageKind Language)
bool isClangFormatOn (StringRef Comment)
bool isClangFormatOff (StringRef Comment)

Variables

IntegerLiteralSeparatorStyle clang::IntegerLiteralSeparator
 Format integer literal separators (' for C++ and _ for C#, Java, and JavaScript).
std::vector< std::string > clang::JavaImportGroups
 A vector of prefixes ordered by the desired groups for Java imports.
JavaScriptQuoteStyle clang::JavaScriptQuotes
 The JavaScriptQuoteStyle to use for JavaScript strings.
bool clang::JavaScriptWrapImports
 Whether to wrap JavaScript import/export statements.
KeepEmptyLinesStyle clang::KeepEmptyLines
 Which empty lines are kept. See MaxEmptyLinesToKeep for how many consecutive empty lines are kept.
bool clang::KeepFormFeed
 This option is deprecated. See AtEndOfFile of KeepEmptyLines.
LambdaBodyIndentationKind clang::LambdaBodyIndentation
 The indentation style of lambda bodies. Signature (the default) causes the lambda body to be indented one additional level relative to the indentation level of the signature. OuterScope forces the lambda body to be indented one additional level relative to the parent scope containing the lambda signature.
LanguageKind clang::Language
 The language that this format style targets.
LineEndingStyle clang::LineEnding
 Line ending style (\n or \r\n) to use.
std::string clang::MacroBlockBegin
 A regular expression matching macros that start a block.
std::string clang::MacroBlockEnd
 A regular expression matching macros that end a block.
std::vector< std::string > clang::Macros
 A list of macros of the form <definition>=<expansion> .
std::vector< std::string > clang::MacrosSkippedByRemoveParentheses
 A vector of function-like macros whose invocations should be skipped by RemoveParentheses.
unsigned clang::MaxEmptyLinesToKeep
 The maximum number of consecutive empty lines to keep.
NamespaceIndentationKind clang::NamespaceIndentation
 The indentation used for namespaces.
std::vector< std::string > clang::NamespaceMacros
 A vector of macros which are used to open namespace blocks.
NumericLiteralCaseStyle clang::NumericLiteralCase
 Capitalization style for numeric literals.
BinPackStyle clang::ObjCBinPackProtocolList
 Controls bin-packing Objective-C protocol conformance list items into as few lines as possible when they go over ColumnLimit.
unsigned clang::ObjCBlockIndentWidth
 The number of characters to use for indentation of ObjC blocks.
bool clang::ObjCBreakBeforeNestedBlockParam
 Break parameters list into lines when there is nested block parameters in a function call.
std::vector< std::string > clang::ObjCPropertyAttributeOrder
 The order in which ObjC property attributes should appear.
bool clang::ObjCSpaceAfterProperty
 Add a space after @property in Objective-C, i.e. use @property (readonly) instead of @property(readonly).
bool clang::ObjCSpaceBeforeProtocolList
 Add a space in front of an Objective-C protocol list, i.e. use Foo <Protocol> instead of Foo<Protocol>.
std::string clang::OneLineFormatOffRegex
 A regular expression that describes markers for turning formatting off for one line. If it matches a comment that is the only token of a line, clang-format skips the comment and the next line. Otherwise, clang-format skips lines containing a matched token.
PackConstructorInitializersStyle clang::PackConstructorInitializers
 The pack constructor initializers style to use.
unsigned clang::PenaltyBreakAssignment
 The penalty for breaking around an assignment operator.
unsigned clang::PenaltyBreakBeforeFirstCallParameter
 The penalty for breaking a function call after call(.
unsigned clang::PenaltyBreakBeforeMemberAccess
 The penalty for breaking before a member access operator (., ->).
unsigned clang::PenaltyBreakComment
 The penalty for each line break introduced inside a comment.
unsigned clang::PenaltyBreakFirstLessLess
 The penalty for breaking before the first <<.
unsigned clang::PenaltyBreakOpenParenthesis
 The penalty for breaking after (.
unsigned clang::PenaltyBreakScopeResolution
 The penalty for breaking after ::.
unsigned clang::PenaltyBreakString
 The penalty for each line break introduced inside a string literal.
unsigned clang::PenaltyBreakTemplateDeclaration
 The penalty for breaking after template declaration.
unsigned clang::PenaltyExcessCharacter
 The penalty for each character outside of the column limit.
unsigned clang::PenaltyIndentedWhitespace
 Penalty for each character of whitespace indentation (counted relative to leading non-whitespace column).
unsigned clang::PenaltyReturnTypeOnItsOwnLine
 Penalty for putting the return type of a function onto its own line.
PointerAlignmentStyle clang::PointerAlignment
 Pointer and reference alignment style.
int clang::PPIndentWidth
 The number of columns to use for indentation of preprocessor statements. When set to -1 (default) IndentWidth is used also for preprocessor statements.
QualifierAlignmentStyle clang::QualifierAlignment
 Different ways to arrange specifiers and qualifiers (e.g. const/volatile).
std::vector< std::string > clang::QualifierOrder
 The order in which the qualifiers appear. The order is an array that can contain any of the following:
std::vector< RawStringFormatclang::RawStringFormats
 Defines hints for detecting supported languages code blocks in raw strings.
ReferenceAlignmentStyle clang::ReferenceAlignment
 Reference alignment style (overrides PointerAlignment for references).
ReflowCommentsStyle clang::ReflowComments
 Comment reformatting style.
bool clang::RemoveBracesLLVM
 Remove optional braces of control statements (if, else, for, and while) in C++ according to the LLVM coding style.
bool clang::RemoveEmptyLinesInUnwrappedLines
 Remove empty lines within unwrapped lines.
RemoveParenthesesStyle clang::RemoveParentheses
 Remove redundant parentheses.
bool clang::RemoveSemicolon
 Remove semicolons after the closing braces of functions and constructors/destructors.
RequiresClausePositionStyle clang::RequiresClausePosition
 The position of the requires clause.
RequiresExpressionIndentationKind clang::RequiresExpressionIndentation
 The indentation used for requires expression bodies.
SeparateDefinitionStyle clang::SeparateDefinitionBlocks
 Specifies the use of empty lines to separate definition blocks, including classes, structs, enums, and functions.
unsigned clang::ShortNamespaceLines
 The maximal number of unwrapped lines that a short namespace spans. Defaults to 1.
bool clang::SkipMacroDefinitionBody
 Do not format macro definition body.
SortIncludesOptions clang::SortIncludes
 Controls if and how clang-format will sort #includes.
SortJavaStaticImportOptions clang::SortJavaStaticImport
 When sorting Java imports, by default static imports are placed before non-static imports. If JavaStaticImportAfterImport is After, static imports are placed after non-static imports.
SortUsingDeclarationsOptions clang::SortUsingDeclarations
 Controls if and how clang-format will sort using declarations.
bool clang::SpaceAfterCStyleCast
 If true, a space is inserted after C style casts.
bool clang::SpaceAfterLogicalNot
 If true, a space is inserted after the logical not operator (!).
bool clang::SpaceAfterOperatorKeyword
 If true, a space will be inserted after the operator keyword.
bool clang::SpaceAfterTemplateKeyword
 If true, a space will be inserted after the template keyword.
SpaceAroundPointerQualifiersStyle clang::SpaceAroundPointerQualifiers
 Defines in which cases to put a space before or after pointer qualifiers.
bool clang::SpaceBeforeAssignmentOperators
 If false, spaces will be removed before assignment operators.
bool clang::SpaceBeforeCaseColon
 If false, spaces will be removed before case colon.
bool clang::SpaceBeforeCpp11BracedList
 If true, a space will be inserted before a C++11 braced list used to initialize an object (after the preceding identifier or type).
bool clang::SpaceBeforeCtorInitializerColon
 If false, spaces will be removed before constructor initializer colon.
bool clang::SpaceBeforeInheritanceColon
 If false, spaces will be removed before inheritance colon.
bool clang::SpaceBeforeJsonColon
 If true, a space will be added before a JSON colon. For other languages, e.g. JavaScript, use SpacesInContainerLiterals instead.
SpaceBeforeParensStyle clang::SpaceBeforeParens
 Defines in which cases to put a space before opening parentheses.
SpaceBeforeParensCustom clang::SpaceBeforeParensOptions
 Control of individual space before parentheses.
bool clang::SpaceBeforeSquareBrackets
 If true, spaces will be before [. Lambdas will not be affected. Only the first [ will get a space added.
bool clang::SpaceBeforeRangeBasedForLoopColon
 If false, spaces will be removed before range-based for loop colon.
SpaceInEmptyBracesStyle clang::SpaceInEmptyBraces
 Specifies when to insert a space in empty braces.
unsigned clang::SpacesBeforeTrailingComments
 If true, spaces may be inserted into (). This option is deprecated. See InEmptyParentheses of SpacesInParensOptions.
SpacesInAnglesStyle clang::SpacesInAngles
 The SpacesInAnglesStyle to use for template argument lists.
bool clang::SpacesInContainerLiterals
 If true, spaces will be inserted around if/for/switch/while conditions. This option is deprecated. See InConditionalStatements of SpacesInParensOptions.
SpacesInLineComment clang::SpacesInLineCommentPrefix
 How many spaces are allowed at the start of a line comment. To disable the maximum set it to -1, apart from that the maximum takes precedence over the minimum.
SpacesInParensStyle clang::SpacesInParens
 If true, spaces will be inserted after ( and before ). This option is deprecated. The previous behavior is preserved by using SpacesInParens with Custom and by setting all SpacesInParensOptions to true except for InCStyleCasts and InEmptyParentheses.
SpacesInParensCustom clang::SpacesInParensOptions
 Control of individual spaces in parentheses.
bool clang::SpacesInSquareBrackets
 If true, spaces will be inserted after [ and before ]. Lambdas without arguments or unspecified size array declarations will not be affected.
LanguageStandard clang::Standard
 Parse and format C++ constructs compatible with this standard.
std::vector< std::string > clang::StatementAttributeLikeMacros
 Macros which are ignored in front of a statement, as if they were an attribute. So that they are not parsed as identifier, for example for Qts emit.
std::vector< std::string > clang::StatementMacros
 A vector of macros that should be interpreted as complete statements.
std::vector< std::string > clang::TableGenBreakingDAGArgOperators
 Works only when TableGenBreakInsideDAGArg is not DontBreak. The string list needs to consist of identifiers in TableGen. If any identifier is specified, this limits the line breaks by TableGenBreakInsideDAGArg option only on DAGArg values beginning with the specified identifiers.
DAGArgStyle clang::TableGenBreakInsideDAGArg
 The styles of the line break inside the DAGArg in TableGen.
unsigned clang::TabWidth
 The number of columns used for tab stops.
std::vector< std::string > clang::TemplateNames
 A vector of non-keyword identifiers that should be interpreted as template names.
std::vector< std::string > clang::TypeNames
 A vector of non-keyword identifiers that should be interpreted as type names.
std::vector< std::string > clang::TypenameMacros
 A vector of macros that should be interpreted as type declarations instead of as function calls.
UseTabStyle clang::UseTab
 The way to use tab characters in the resulting file.
std::vector< std::string > clang::VariableTemplates
 A vector of non-keyword identifiers that should be interpreted as variable template names.
bool clang::VerilogBreakBetweenInstancePorts
 For Verilog, put each port on its own line in module instantiations.
std::vector< std::string > clang::WhitespaceSensitiveMacros
 A vector of macros which are whitespace-sensitive and should not be touched.
WrapNamespaceBodyWithEmptyLinesStyle clang::WrapNamespaceBodyWithEmptyLines
 Wrap namespace body with empty lines.
const char * StyleOptionHelpDescription
 Description to be used for help text for a llvm::cl option for specifying format style. The description is closely related to the operation of getStyle().
const char * DefaultFormatStyle
 The suggested format style to use by default. This allows tools using getStyle to have a consistent default style. Different builds can modify the value to the preferred styles.
const char * DefaultFallbackStyle
 The suggested predefined style to use as the fallback style in getStyle. Different builds can modify the value to the preferred styles.

Detailed Description

Various functions to configurably format source code.

Definition in file Format.h.

Function Documentation

◆ cleanup()

tooling::Replacements cleanup ( const FormatStyle & Style,
StringRef Code,
ArrayRef< tooling::Range > Ranges,
StringRef FileName = "<stdin>" )

◆ cleanupAroundReplacements()

Expected< tooling::Replacements > cleanupAroundReplacements ( StringRef Code,
const tooling::Replacements & Replaces,
const FormatStyle & Style )

Returns the replacements corresponding to applying Replaces and cleaning up the code after that on success; otherwise, return an llvm::Error carrying llvm::StringError. This also supports inserting/deleting C++ #include directives:

  • If a replacement has offset UINT_MAX, length 0, and a replacement text that is an #include directive, this will insert the #include into the correct block in the Code.
  • If a replacement has offset UINT_MAX, length 1, and a replacement text that is the name of the header to be removed, the header will be removed from Code if it exists. The include manipulation is done via tooling::HeaderInclude, see its documentation for more details on how include insertion points are found and what edits are produced.

◆ configurationAsText()

std::string configurationAsText ( const FormatStyle & Style)

Gets configuration in a YAML string.

◆ fixNamespaceEndComments()

tooling::Replacements fixNamespaceEndComments ( const FormatStyle & Style,
StringRef Code,
ArrayRef< tooling::Range > Ranges,
StringRef FileName = "<stdin>" )

Fix namespace end comments in the given Ranges in Code.

Returns the Replacements that fix the namespace comments in all Ranges in Code.

◆ formatReplacements()

Expected< tooling::Replacements > formatReplacements ( StringRef Code,
const tooling::Replacements & Replaces,
const FormatStyle & Style )

Returns the replacements corresponding to applying and formatting Replaces on success; otheriwse, return an llvm::Error carrying llvm::StringError.

◆ getChromiumStyle()

FormatStyle getChromiumStyle ( FormatStyle::LanguageKind Language)

Returns a format style complying with Chromium's style guide: http://www.chromium.org/developers/coding-style.

◆ getClangFormatStyle()

FormatStyle getClangFormatStyle ( )

◆ getFormattingLangOpts()

LangOptions getFormattingLangOpts ( const FormatStyle & Style = getLLVMStyle())

Returns the LangOpts that the formatter expects you to set.

Parameters
Styledetermines specific settings for lexing mode.

References DefaultFallbackStyle, DefaultFormatStyle, and StyleOptionHelpDescription.

◆ getGNUStyle()

FormatStyle getGNUStyle ( )

Returns a format style complying with GNU Coding Standards: http://www.gnu.org/prep/standards/standards.html.

◆ getGoogleStyle()

FormatStyle getGoogleStyle ( FormatStyle::LanguageKind Language)

◆ getLanguageName()

StringRef getLanguageName ( FormatStyle::LanguageKind Language)
inline

◆ getLLVMStyle()

FormatStyle getLLVMStyle ( FormatStyle::LanguageKind Language = FormatStyle::LK_Cpp)

Returns a format style complying with the LLVM coding standards: http://llvm.org/docs/CodingStandards.html.

◆ getMicrosoftStyle()

FormatStyle getMicrosoftStyle ( FormatStyle::LanguageKind Language)

◆ getMozillaStyle()

FormatStyle getMozillaStyle ( )

Returns a format style complying with Mozilla's style guide: https://firefox-source-docs.mozilla.org/code-quality/coding-style/index.html.

◆ getNoStyle()

FormatStyle getNoStyle ( )

Returns style indicating formatting should be not applied at all.

◆ getPredefinedStyle()

bool getPredefinedStyle ( StringRef Name,
FormatStyle::LanguageKind Language,
FormatStyle * Style )

Gets a predefined style for the specified language by name.

Currently supported names: LLVM, Google, Chromium, Mozilla. Names are compared case-insensitively.

Returns true if the Style has been set.

Referenced by llvm::yaml::MappingTraits< FormatStyle >::mapping().

◆ getStyle()

Expected< FormatStyle > getStyle ( StringRef StyleName,
StringRef FileName,
StringRef FallbackStyle,
StringRef Code = "",
llvm::vfs::FileSystem * FS = nullptr,
bool AllowUnknownOptions = false,
llvm::SourceMgr::DiagHandlerTy DiagHandler = nullptr )

Construct a FormatStyle based on StyleName.

StyleName can take several forms:

  • "{<key>: <value>, ...}" - Set specic style parameters.
  • "<style name>" - One of the style names supported by getPredefinedStyle().
  • "file" - Load style configuration from a file called .clang-format located in one of the parent directories of FileName or the current directory if FileName is empty.
  • "file:<format_file_path>" to explicitly specify the configuration file to use.
Parameters
[in]StyleNameStyle name to interpret according to the description above.
[in]FileNamePath to start search for .clang-format if StyleName == "file".
[in]FallbackStyleThe name of a predefined style used to fallback to in case StyleName is "file" and no file can be found.
[in]CodeThe actual code to be formatted. Used to determine the language if the filename isn't sufficient.
[in]FSThe underlying file system, in which the file resides. By default, the file system is the real file system.
[in]AllowUnknownOptionsIf true, unknown format options only emit a warning. If false, errors are emitted on unknown format options.
Returns
FormatStyle as specified by StyleName. If StyleName is "file" and no file is found, returns FallbackStyle. If no style could be determined, returns an Error.

◆ getWebKitStyle()

FormatStyle getWebKitStyle ( )

Returns a format style complying with Webkit's style guide: http://www.webkit.org/coding/coding-style.html.

◆ guessLanguage()

FormatStyle::LanguageKind guessLanguage ( StringRef FileName,
StringRef Code )

◆ isClangFormatOff()

bool isClangFormatOff ( StringRef Comment)

◆ isClangFormatOn()

bool isClangFormatOn ( StringRef Comment)

◆ parseConfiguration() [1/2]

std::error_code parseConfiguration ( llvm::MemoryBufferRef Config,
FormatStyle * Style,
bool AllowUnknownOptions = false,
llvm::SourceMgr::DiagHandlerTy DiagHandler = nullptr,
void * DiagHandlerCtx = nullptr,
bool IsDotHFile = false )

Parse configuration from YAML-formatted text.

Style->Language is used to get the base style, if the BasedOnStyle option is present.

The FormatStyleSet of Style is reset.

When BasedOnStyle is not present, options not present in the YAML document, are retained in Style.

If AllowUnknownOptions is true, no errors are emitted if unknown format options are occurred.

If set all diagnostics are emitted through the DiagHandler.

◆ parseConfiguration() [2/2]

std::error_code parseConfiguration ( StringRef Config,
FormatStyle * Style,
bool AllowUnknownOptions = false,
bool IsDotHFile = false )
inline

Like above but accepts an unnamed buffer.

Definition at line 5749 of file Format.h.

References clang::format::parseConfiguration().

◆ reformat() [1/2]

tooling::Replacements reformat ( const FormatStyle & Style,
StringRef Code,
ArrayRef< tooling::Range > Ranges,
StringRef FileName,
bool * IncompleteFormat )

Same as above, except if IncompleteFormat is non-null, its value will be set to true if any of the affected ranges were not formatted due to a non-recoverable syntax error.

◆ reformat() [2/2]

tooling::Replacements reformat ( const FormatStyle & Style,
StringRef Code,
ArrayRef< tooling::Range > Ranges,
StringRef FileName = "<stdin>",
FormattingAttemptStatus * Status = nullptr )

Reformats the given Ranges in Code.

Each range is extended on either end to its next bigger logic unit, i.e. everything that might influence its formatting or might be influenced by its formatting.

Returns the Replacements necessary to make all Ranges comply with Style.

If Status is non-null, its value will be populated with the status of this formatting attempt. See FormattingAttemptStatus.

◆ separateDefinitionBlocks()

tooling::Replacements separateDefinitionBlocks ( const FormatStyle & Style,
StringRef Code,
ArrayRef< tooling::Range > Ranges,
StringRef FileName = "<stdin>" )

Inserts or removes empty lines separating definition blocks including classes, structs, functions, namespaces, and enums in the given Ranges in Code.

Returns the Replacements that inserts or removes empty lines separating definition blocks in all Ranges in Code.

◆ sortIncludes()

tooling::Replacements sortIncludes ( const FormatStyle & Style,
StringRef Code,
ArrayRef< tooling::Range > Ranges,
StringRef FileName,
unsigned * Cursor = nullptr )

Returns the replacements necessary to sort all #include blocks that are affected by Ranges.

◆ sortUsingDeclarations()

tooling::Replacements sortUsingDeclarations ( const FormatStyle & Style,
StringRef Code,
ArrayRef< tooling::Range > Ranges,
StringRef FileName = "<stdin>" )

Sort consecutive using declarations in the given Ranges in Code.

Returns the Replacements that sort the using declarations in all Ranges in Code.

Variable Documentation

◆ DefaultFallbackStyle

const char* DefaultFallbackStyle
extern

The suggested predefined style to use as the fallback style in getStyle. Different builds can modify the value to the preferred styles.

Referenced by getFormattingLangOpts().

◆ DefaultFormatStyle

const char* DefaultFormatStyle
extern

The suggested format style to use by default. This allows tools using getStyle to have a consistent default style. Different builds can modify the value to the preferred styles.

Referenced by getFormattingLangOpts().

◆ StyleOptionHelpDescription

const char* StyleOptionHelpDescription
extern

Description to be used for help text for a llvm::cl option for specifying format style. The description is closely related to the operation of getStyle().

Referenced by getFormattingLangOpts().