Kotlin linter in spirit of feross/standard (JavaScript) and gofmt (Go).
- No configuration.* Which means no decisions to make, nothing to argue about and no special files to manage.
While this might sound extreme, keep in mind thatktlint
tries to capture (reflect) official code style* from kotlinlang.org and Android Kotlin Style Guide (+ we respect your .editorconfig and support additional ruleset|s). - Built-in formatter. So that you wouldn't have to fix all style violations by hand.
- Customizable output.
plain
(+plain?group_by_file
),json
,html
andcheckstyle
reporters are available out-of-the-box. It's also easy to create your own. - A single executable jar with all dependencies included.
Installation | Usage | Integration with Maven / Gradle / IntelliJ IDEA / Emacs / Continuous Integration | Creating a ruleset | a reporter | Badge | FAQ
chain-wrapping
: When wrapping chained calls.
,?.
and?:
should be placed on the next linecomment-spacing
: The end of line comment sign//
should be preceded and followed by exactly a spacefilename
: Files containing only one toplevel domain should be named according to that element.final-newline
: Newline at the end of each file (enabled by default) (setinsert_final_newline=false
in .editorconfig to disable (see EditorConfig section for more)).import-ordering
: Imports ordered consistently (see Custom ktlint EditorConfig properties for more)indent
: Indentation formatting - respects.editorconfig
indent_size
with no continuation indent (see EditorConfig section for more)max-line-length
: Ensures that lines do not exceed the given length of.editorconfig
propertymax_line_length
(see EditorConfig section for more). This rule does not apply in a number of situations. For example, in the case a line exceeds the maximum line length due to and comment that disables ktlint rules than that comment is being ignored when validating the length of the line. The.editorconfig
propertyktlint_ignore_back_ticked_identifier
can be set to ignore identifiers which are enclosed in backticks, which for example is very useful when you want to allow longer names for unit tests.modifier-order
: Consistent order of modifiersno-blank-line-before-rbrace
: No blank lines before}
no-consecutive-blank-lines
: No consecutive blank linesno-empty-class-body
: No empty ({}
) class bodiesno-line-break-after-else
: Disallows line breaks after the else keyword if that could lead to confusion, for example:if (conditionA()) { doSomething() } else if (conditionB()) { doAnotherThing() }
no-line-break-before-assignment
: When a line is broken at an assignment (=
) operator the break comes after the symbolno-multi-spaces
: Except in indentation and in KDoc's it is not allowed to have multiple consecutive spacesno-semi
: No semicolons (unless used to separate multiple statements on the same line)no-trailing-spaces
: No trailing whitespacesno-unit-return
: NoUnit
returns (fun fn {}
instead offun fn: Unit {}
)no-unused-imports
: No unusedimport
sno-wildcard-imports
: No wildcardimport
s expect imports listed in.editorconfig
propertyij_kotlin_packages_to_use_import_on_demand
parameter-list-wrapping
: When class/function signature doesn't fit on a single line, each parameter must be on a separate linestring-template
: Consistent string templates ($v
instead of${v}
,${p.v}
instead of${p.v.toString()}
)
colon-spacing
: Consistent spacing around coloncomma-spacing
: Consistent spacing around commacurly-spacing
: Consistent spacing around curly bracesdot-spacing
: Consistent spacing around dotskeyword-spacing
: Consistent spacing around keywordsop-spacing
: Consistent spacing around operatorsparen-spacing
: Consistent spacing around parenthesisrange-spacing
: Consistent spacing around range operators
New rules will be added into the experimental ruleset, which can be enabled
by passing the --experimental
flag to ktlint
.
experimental:annotation
: Annotation formatting - multiple annotations should be on a separate line than the annotated declaration; annotations with parameters should each be on separate lines; annotations should be followed by a spaceexperimental:block-comment-initial-star-alignment
: Lines in a block comment which (exclusive the indentation) start with a*
should have this*
aligned with the*
in the opening of the block comment.experimental:discouraged-comment-location
: Detect discouraged comment locations (no autocorrect)experimental:enum-entry-name-case
: Enum entry names should be uppercase underscore-separated namesexperimental:multiline-if-else
: Braces required for multiline if/else statementsexperimental:no-empty-first-line-in-method-block
: No leading empty lines in method blocksexperimental:package-name
: No underscores in package namesexperimental:parameter-list-spacing
: Consistent spacing inside the parameter listexperimental:unnecessary-parentheses-before-trailing-lambda
: An empty parentheses block before a lambda is redundant. For examplesome-string".count() { it == '-' }
function-signature
: rewrites the function signature to a single line when possible (e.g. when not exceeding themax_line_length
property) or a multiline signature otherwise. In case of function with a body expression, the body expression is placed on the same line as the function signature when not exceeding themax_line_length
property. Optionally the function signature can be forced to be written as a multiline signature in case the function has more than a specified number of parameters (.editorconfig' property
ktlint_function_signature_wrapping_rule_always_with_minimum_parameters`)
experimental:annotation-spacing
: Annotations should be separated by the annotated declaration by a single line breakexperimental:double-colon-spacing
: No spaces around::
experimental:fun-keyword-spacing
: Consistent spacing after the fun keywordexperimental:function-return-type-spacing
: Consistent spacing around the function return typeexperimental:function-start-of-body-spacing
: Consistent spacing before start of function bodyexperimental:function-type-reference-spacing
: Consistent spacing in the type reference before a functionexperimental:modifier-list-spacing
: Consistent spacing between modifiers in and after the last modifier in a modifier listexperimental:nullable-type-spacing
: No spaces in a nullable typeexperimental:spacing-around-angle-brackets
: No spaces around angle bracketsexperimental:spacing-between-declarations-with-annotations
: Declarations with annotations should be separated by a blank lineexperimental:spacing-between-declarations-with-comments
: Declarations with comments should be separated by a blank lineexperimental:spacing-between-function-name-and-opening-parenthesis
: Consistent spacing between function name and opening parenthesisexperimental:type-parameter-list-spacing
: Spacing after a type parameter list in function and class declarationsexperimental:unary-op-spacing
: No spaces around unary operators
experimental:argument-list-wrapping
: Argument list wrappingexperimental:comment-wrapping
: A block comment should start and end on a line that does not contain any other element. A block comment should not be used as end of line comment.experimental:kdoc-wrapping
: A KDoc comment should start and end on a line that does not contain any other element.
ktlint recognizes the following .editorconfig properties (provided they are specified under [*.{kt,kts}]
):
(values shown below are the defaults and do not need to be specified explicitly)
[*.{kt,kts}]
# possible values: number (e.g. 2), "unset" (makes ktlint ignore indentation completely)
indent_size=4
# true (recommended) / false
insert_final_newline=true
# possible values: number (e.g. 120) (package name, imports & comments are ignored), "off"
# it's automatically set to 100 on `ktlint --android ...` (per Android Kotlin Style Guide)
max_line_length=off
Unfortunately IntelliJ IDEA has .editorconfig
autoformat issue
that adds additional space into glob statements.
For example, [*{kt,kts}]
is formatted into [*{kt, kts}]
(original ktlint issue).
Such behaviour violates .editorconfig
specification and leads to ignoring this section when ktlint is parsing it.
# Comma-separated list of rules to disable (Since 0.34.0)
# Note that rules in any ruleset other than the standard ruleset will need to be prefixed
# by the ruleset identifier.
disabled_rules=no-wildcard-imports,experimental:annotation,my-custom-ruleset:my-custom-rule
# Defines the imports layout. The layout can be composed by the following symbols:
# "*" - wildcard. There must be at least one entry of a single wildcard to match all other imports. Matches anything after a specified symbol/import as well.
# "|" - blank line. Supports only single blank lines between imports. No blank line is allowed in the beginning or end of the layout.
# "^" - alias import, e.g. "^android.*" will match all android alias imports, "^" will match all other alias imports.
# import paths - these can be full paths, e.g. "java.util.List.*" as well as wildcard paths, e.g. "kotlin.**"
# Examples (we use ij_kotlin_imports_layout to set an imports layout for both ktlint and IDEA via a single property):
ij_kotlin_imports_layout=* # alphabetical with capital letters before lower case letters (e.g. Z before a), no blank lines
ij_kotlin_imports_layout=*,java.**,javax.**,kotlin.**,^ # default IntelliJ IDEA style, same as alphabetical, but with "java", "javax", "kotlin" and alias imports in the end of the imports list
ij_kotlin_imports_layout=android.**,|,^org.junit.**,kotlin.io.Closeable.*,|,*,^ # custom imports layout
# According to https://kotlinlang.org/docs/reference/coding-conventions.html#names-for-test-methods it is acceptable to write method names
# in natural language. When using natural language, the description tends to be longer. Allow lines containing an identifier between
# backticks to be longer than the maximum line length. (Since 0.41.0)
[**/test/**.kt]
ktlint_ignore_back_ticked_identifier=true
# Comma-separated list of allowed wildcard imports that will override the no-wildcard-imports rule.
# This can be used for allowing wildcard imports from libraries like Ktor where extension functions are used in a way that creates a lot of imports.
# "**" applies to package and all subpackages
ij_kotlin_packages_to_use_import_on_demand=java.util.* # allow java.util.* as wildcard import
ij_kotlin_packages_to_use_import_on_demand=io.ktor.** # allow wildcard import from io.ktor.* and all subpackages
You could override properties for specific directories inside your project:
[*.{kt,kts}]
disabled_rules=import-ordering
# Note that in this case 'import-ordering' rule will be active and 'indent' will be disabled
[api/*.{kt,kts}]
disabled_rules=indent
You can try ktlint
online here using the standard or a custom ruleset without installing it to your PC.
To contribute or get more info, please visit the GitHub repository.
Skip all the way to the "Integration" section if you don't plan to use
ktlint
's command line interface.
curl -sSLO https://github.com/pinterest/ktlint/releases/download/0.45.2/ktlint &&
chmod a+x ktlint &&
sudo mv ktlint /usr/local/bin/
... or just download ktlint
from the releases page
ktlint.asc
contains PGP signature which you can verify with:- (Releases up through 0.31.0)
curl -sS https://keybase.io/shyiko/pgp_keys.asc | gpg --import && gpg --verify ktlint.asc
- (Releases from 0.32.0 on)
curl -sS https://keybase.io/ktlint/pgp_keys.asc | gpg --import && gpg --verify ktlint.asc
- (Releases up through 0.31.0)
On macOS (or Linux) you can also use brew - brew install ktlint
- or MacPorts - port install ktlint
.
On Arch Linux, you can install ktlint AUR.
If you don't have curl installed - replace
curl -sL
withwget -qO-
.
If you are behind a proxy see - curl / wget manpage. Usually simple
http_proxy=http://proxy-server:port https_proxy=http://proxy-server:port curl -sL ...
is enough.
# Get help about all available commands
$ ktlint --help
# Check the style of all Kotlin files (ending with '.kt' or '.kts') inside the current dir (recursively).
# Hidden folders will be skipped.
$ ktlint
# Check only certain locations starting from the current directory.
#
# Prepend ! to negate the pattern, KtLint uses .gitignore pattern style syntax.
# Globs are applied starting from the last one.
#
# Hidden folders will be skipped.
# Check all '.kt' files in 'src/' directory, but ignore files ending with 'Test.kt':
ktlint "src/**/*.kt" "!src/**/*Test.kt"
# Check all '.kt' files in 'src/' directory, but ignore 'generated' directory and its subdirectories:
ktlint "src/**/*.kt" "!src/**/generated/**"
# Auto-correct style violations.
# If some errors cannot be fixed automatically they will be printed to stderr.
$ ktlint -F "src/**/*.kt"
# Print style violations grouped by file.
$ ktlint --reporter=plain?group_by_file
# Print style violations as usual + create report in checkstyle format, specifying report location.
$ ktlint --reporter=plain --reporter=checkstyle,output=ktlint-report-in-checkstyle-format.xml
# Check against a baseline file.
$ ktlint --baseline=ktlint-baseline.xml
# Install git hook to automatically check files for style violations on commit.
# Run "ktlint installGitPrePushHook" if you wish to run ktlint on push instead.
$ ktlint installGitPreCommitHook
on Windows you'll have to use
java -jar ktlint ...
.
ktlint --help
for more.
... with Maven
pom.xml
...
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.8</version>
<executions>
<execution>
<id>ktlint</id>
<phase>verify</phase>
<configuration>
<target name="ktlint">
<java taskname="ktlint" dir="${basedir}" fork="true" failonerror="true"
classpathref="maven.plugin.classpath" classname="com.pinterest.ktlint.Main">
<arg value="src/**/*.kt"/>
<!-- to generate report in checkstyle format prepend following args: -->
<!--
<arg value="--reporter=plain"/>
<arg value="--reporter=checkstyle,output=${project.build.directory}/ktlint.xml"/>
-->
<!-- see https://github.com/pinterest/ktlint#usage for more -->
</java>
</target>
</configuration>
<goals><goal>run</goal></goals>
</execution>
<execution>
<id>ktlint-format</id>
<configuration>
<target name="ktlint">
<java taskname="ktlint" dir="${basedir}" fork="true" failonerror="true"
classpathref="maven.plugin.classpath" classname="com.pinterest.ktlint.Main">
<arg value="-F"/>
<arg value="src/**/*.kt"/>
</java>
</target>
</configuration>
<goals><goal>run</goal></goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>com.pinterest</groupId>
<artifactId>ktlint</artifactId>
<version>0.45.2</version>
</dependency>
<!-- additional 3rd party ruleset(s) can be specified here -->
</dependencies>
</plugin>
...
If you want ktlint to run before code compilation takes place - change
<phase>verify</phase>
to<phase>validate</phase>
(see Maven Build Lifecycle for more).
To check code style - mvn antrun:run@ktlint
(it's also bound to mvn verify
).
To run formatter - mvn antrun:run@ktlint-format
.
Another option is to use a dedicated Maven plugin - gantsign/ktlint-maven-plugin.
... with Gradle
Gradle plugins (in order of appearance):
-
jlleitschuh/ktlint-gradle
Gradle plugin that automatically creates check and format tasks for project Kotlin sources, supports different kotlin plugins and Gradle build caching. -
jeremymailen/kotlinter-gradle
Gradle plugin featuring incremental build support, file reports, and*.kts
source support.
You might also want to take a look at diffplug/spotless or autostyle/autostyle that have a built-in support for ktlint. In addition to linting/formatting kotlin code it allows you to keep license headers, markdown documentation, etc. in check.
build.gradle
// kotlin-gradle-plugin must be applied for configuration below to work
// (see https://kotlinlang.org/docs/reference/using-gradle.html)
apply plugin: 'java'
repositories {
mavenCentral()
}
configurations {
ktlint
}
dependencies {
ktlint("com.pinterest:ktlint:0.45.2") {
attributes {
attribute(Bundling.BUNDLING_ATTRIBUTE, getObjects().named(Bundling, Bundling.EXTERNAL))
}
}
// additional 3rd party ruleset(s) can be specified here
// just add them to the classpath (e.g. ktlint 'groupId:artifactId:version') and
// ktlint will pick them up
}
task ktlint(type: JavaExec, group: "verification") {
description = "Check Kotlin code style."
classpath = configurations.ktlint
mainClass.set("com.pinterest.ktlint.Main")
args "src/**/*.kt"
// to generate report in checkstyle format prepend following args:
// "--reporter=plain", "--reporter=checkstyle,output=${buildDir}/ktlint.xml"
// to add a baseline to check against prepend following args:
// "--baseline=ktlint-baseline.xml"
// see https://github.com/pinterest/ktlint#usage for more
}
check.dependsOn ktlint
task ktlintFormat(type: JavaExec, group: "formatting") {
description = "Fix Kotlin code style deviations."
classpath = configurations.ktlint
mainClass.set("com.pinterest.ktlint.Main")
args "-F", "src/**/*.kt"
}
To check code style - gradle ktlint
(it's also bound to gradle check
).
To run formatter - gradle ktlintFormat
.
See Making your Gradle tasks incremental by Niklas Baudy on how to make tasks above incremental.
build.gradle.kts
val ktlint by configurations.creating
dependencies {
ktlint("com.pinterest:ktlint:0.45.2") {
attributes {
attribute(Bundling.BUNDLING_ATTRIBUTE, objects.named(Bundling.EXTERNAL))
}
}
// ktlint(project(":custom-ktlint-ruleset")) // in case of custom ruleset
}
val outputDir = "${project.buildDir}/reports/ktlint/"
val inputFiles = project.fileTree(mapOf("dir" to "src", "include" to "**/*.kt"))
val ktlintCheck by tasks.creating(JavaExec::class) {
inputs.files(inputFiles)
outputs.dir(outputDir)
description = "Check Kotlin code style."
classpath = ktlint
mainClass.set("com.pinterest.ktlint.Main")
args = listOf("src/**/*.kt")
}
val ktlintFormat by tasks.creating(JavaExec::class) {
inputs.files(inputFiles)
outputs.dir(outputDir)
description = "Fix Kotlin code style deviations."
classpath = ktlint
mainClass.set("com.pinterest.ktlint.Main")
args = listOf("-F", "src/**/*.kt")
}
... with IntelliJ IDEA
It is recommended to align the settings of IntelliJ IDEA's built-in formatter with ktlint. This reduces the chance that code which is formatted by ktlint conflicts with formatting by the IntelliJ IDEA built-in formatter.
Choose any of options below to align the formatting settings of IntelliJ IDEA.
Use ktlint to change the code style of a single project with any of the commands below.
# Run command below from root directory of project
ktlint applyToIDEAProject
Or if you want to use android specific code style:
# Run command below from root directory of project
ktlint --android applyToIDEAProject
Use ktlint to change the code style of all projects with any of the commands below.
ktlint applyToIDEA
Or if you want to use android specific code style:
ktlint --android applyToIDEA
Create or update the code style config with .editorconfig
by setting properties below:
[{*.kt,*.kts}]
ij_kotlin_code_style_defaults = KOTLIN_OFFICIAL
ij_kotlin_line_comment_at_first_column = false
ij_kotlin_line_comment_add_space = true
# These options can keep to use single name import
ij_kotlin_name_count_to_use_star_import = 2147483647
ij_kotlin_name_count_to_use_star_import_for_members = 2147483647
ij_kotlin_keep_blank_lines_in_declarations = 1
ij_kotlin_keep_blank_lines_in_code = 1
ij_kotlin_keep_blank_lines_before_right_brace = 0
# optional but recommended
ij_kotlin_align_multiline_parameters = false
# optional but recommended
ij_continuation_indent_size = 4
# Android specific rules
ij_kotlin_import_nested_classes = false
ij_kotlin_imports_layout = *,^
Go to File -> Settings... -> Editor
- General -> Auto Import
- check
Kotlin
/Optimize imports on the fly (for current project)
.
- check
- Code Style -> Kotlin
- Set from... on the right -> (Predefined style) -> Kotlin style guide (Kotlin plugin 1.2.20+).
- open Code Generation tab
- uncheck
Line comment at first column
; - select
Add a space at comment start
.
- uncheck
- open Imports tab
- select
Use single name import
(all of them); - remove
import java.util.*
fromPackages to Use Import with '*'
.
- select
- open Blank Lines tab
- change
Keep Maximum Blank Lines
/In declarations
&In code
to 1 andBefore '}'
to 0.
- change
- (optional but recommended) open Wrapping and Braces tab
- uncheck
Function declaration parameters
(ORMethods declartion parameters
for older version) /Align when multiline
.
- uncheck
- (optional but recommended) open Tabs and Indents tab
- change
Continuation indent
to the same value asIndent
(4 by default).
- change
- Inspections
- change
Severity
level ofUnused import directive
andRedundant semicolon
underKotlin
->Redundant constructs
toERROR
.
- change
... with GNU Emacs
... with Vim
See w0rp/ale.
Integrated with something else? Send a PR.
See Mega-Linter: 70+ linters aggregated in a single tool for CI, including ktlint activated out of the box
See also Writing your first ktlint rule by Niklas Baudy.
In a nutshell: "ruleset" is a JAR containing one or more Rules gathered together in a RuleSet. ktlint
is relying on
ServiceLoader to discover all available "RuleSet"s
on the classpath (as a ruleset author, all you need to do is to include a META-INF/services/com.pinterest.ktlint.core.RuleSetProvider
file
containing a fully qualified name of your RuleSetProvider implementation).
Once packaged in a JAR e.g. via ./gradlew build
you can load it with
# enable additional 3rd party ruleset by pointing ktlint to its location on the file system
$ ktlint -R /path/to/custom/rulseset.jar "src/test/**/*.kt"
Loading custom (3rd party) ruleset via built-in maven dependency resolver is deprecated, see pinterest#451.
A complete sample project (with tests and build files) is included in this repo under the ktlint-ruleset-template directory (make sure to check NoVarRuleTest as it contains some useful information).
While writing/debugging Rules it's often helpful to have an AST
printed out to see the structure rules have to work with. ktlint >= 0.15.0 has a printAST
subcommand (or --print-ast
flag for ktlint < 0.34.0) specifically for this purpose
(usage: ktlint --color printAST <file>
).
An example of the output is shown below.
$ printf "fun main() {}" | ktlint --color printAST --stdin
1: ~.psi.KtFile (~.psi.stubs.elements.KtFileElementType.kotlin.FILE)
1: ~.psi.KtPackageDirective (~.psi.stubs.elements.KtPlaceHolderStubElementType.PACKAGE_DIRECTIVE) ""
1: ~.psi.KtImportList (~.psi.stubs.elements.KtPlaceHolderStubElementType.IMPORT_LIST) ""
1: ~.psi.KtScript (~.psi.stubs.elements.KtScriptElementType.SCRIPT)
1: ~.psi.KtBlockExpression (~.KtNodeType.BLOCK)
1: ~.psi.KtNamedFunction (~.psi.stubs.elements.KtFunctionElementType.FUN)
1: ~.c.i.p.impl.source.tree.LeafPsiElement (~.lexer.KtKeywordToken.fun) "fun"
1: ~.c.i.p.impl.source.tree.PsiWhiteSpaceImpl (~.c.i.p.tree.IElementType.WHITE_SPACE) " "
1: ~.c.i.p.impl.source.tree.LeafPsiElement (~.lexer.KtToken.IDENTIFIER) "main"
1: ~.psi.KtParameterList
(~.psi.stubs.elements.KtPlaceHolderStubElementType.VALUE_PARAMETER_LIST)
1: ~.c.i.p.impl.source.tree.LeafPsiElement (~.lexer.KtSingleValueToken.LPAR) "("
1: ~.c.i.p.impl.source.tree.LeafPsiElement (~.lexer.KtSingleValueToken.RPAR) ")"
1: ~.c.i.p.impl.source.tree.PsiWhiteSpaceImpl (~.c.i.p.tree.IElementType.WHITE_SPACE) " "
1: ~.psi.KtBlockExpression (~.KtNodeType.BLOCK)
1: ~.c.i.p.impl.source.tree.LeafPsiElement (~.lexer.KtSingleValueToken.LBRACE) "{"
1: ~.c.i.p.impl.source.tree.LeafPsiElement (~.lexer.KtSingleValueToken.RBRACE) "}"
format: <line_number:> <node.psi::class> (<node.elementType>) "<node.text>"
legend: ~ = org.jetbrains.kotlin, c.i.p = com.intellij.psi
Take a look at ktlint-reporter-plain.
In short, all you need to do is to implement a
Reporter and make it available by registering
a custom ReporterProvider using
META-INF/services/com.pinterest.ktlint.core.ReporterProvider
. Pack all of that into a JAR and you're done.
To load a custom (3rd party) reporter use ktlint --reporter=name,artifact=/path/to/custom-ktlint-reporter.jar
(see ktlint --help
for more).
Loading custom (3rd party) reporter via built-in maven dependency resolver is deprecated, see pinterest#451.
Third-party:
[![ktlint](https://img.shields.io/badge/code%20style-%E2%9D%A4-FF4081.svg)](https://ktlint.github.io/)
Simplicity.
Spending time on configuration (& maintenance down the road) of hundred-line long style config file(s) is counter-productive. Instead of wasting your energy on something that has no business value - focus on what really matters (not debating whether to use tabs or spaces).
By using ktlint you put the importance of code clarity and community conventions over personal preferences. This makes things easier for people reading your code as well as frees you from having to document & explain what style potential contributor(s) have to follow.
ktlint is a single binary with both linter & formatter included. All you need is to drop it in (no need to get overwhelmed while choosing among dozens of code style options).
Absolutely, "no configuration" doesn't mean "no extensibility". You can add your own ruleset(s) to discover potential bugs, check for anti-patterns, etc.
See Creating A Ruleset.
This is meant primarily as an escape latch for the rare cases when ktlint is not able to produce the correct result (please report any such instances using GitHub Issues).
To disable a specific rule you'll need the rule identifier which is displayed at the end of the lint error. Note that when the rule id is prefixed with a rule set id like experimental
, you will need to use that fully qualified rule id.
An error can be suppressed using:
- EOL comments
- Block comments
- @Suppress annotations
From a consistency perspective seen, it might be best to not mix the (EOL/Block) comment style with the annotation style in the same project.
Important notice: some rules like the indent
rule do not yet support disabling of the rule per line of block.
An error for a specific rule on a specific line can be disabled with an EOL comment on that line:
import package.* // ktlint-disable no-wildcard-imports
In case lint errors for different rules on the same line need to be ignored, then specify multiple rule ids (separated by a space):
import package.* // ktlint-disable no-wildcard-imports other-rule-id
In case all lint errors on a line need to be ignored, then do not specify the rule id at all:
import package.* // ktlint-disable
An error for a specific rule in a block of lines can be disabled with an block comment like:
/* ktlint-disable no-wildcard-imports */
import package.a.*
import package.b.*
/* ktlint-enable no-wildcard-imports */
In case lint errors for different rules in the same block of lines need to be ignored, then specify multiple rule ids (separated by a space):
/* ktlint-disable no-wildcard-imports other-rule-id */
import package.a.*
import package.b.*
/* ktlint-enable no-wildcard-imports,other-rule-id */
Note that the ktlint-enable
directive needs to specify the exact same rule-id's and in the same order as the ktlint-disable
directive.
In case all lint errors in a block of lines needs to be ignored, then do not specify the rule id at all:
/* ktlint-disable */
import package.a.*
import package.b.*
/* ktlint-enable */
As of ktlint version 0.46, it is possible to specify any ktlint rule id via the
@Suppress
annotation in order to suppress errors found by that rule. Note that some rules likeindent
still do not support disabling for parts of a file.
An error for a specific rule on a specific line can be disabled with a @Suppress
annotation:
@Suppress("ktlint:max-line-length","ktlint:experimental:trailing-comma")
val foo = listOf(
"some really looooooooooooooooong string exceeding the max line length",
)
Note that when using @Suppress
each qualified rule id needs to be prefixed with ktlint:
.
To suppress the violations of all ktlint rules, use:
@Suppress("ktlint")
val foo = "some really looooooooooooooooong string exceeding the max line length"
Like with other @Suppress
annotations, it can be placed on targets supported by the annotation.
See the EditorConfig section for details on how to use the disabled_rules
property.
You may also pass a list of disabled rules via the --disabled_rules
command line flag. It has the same syntax as the EditorConfig property.
Make sure to read CONTRIBUTING.md.
git clone https://github.com/pinterest/ktlint && cd ktlint
./gradlew tasks # shows how to build, test, run, etc. project
To open ktlint in Intellij IDEA:
File -> Open... (you may need to right-click onpom.xml
(in the project dir) and then Maven -> Reimport).
You'll also need to set "Project SDK" to 1.8, "Project language level" to 8 in "Project Settings" (File -> Project Structure...).
To runktlint
- right-click onktlint/src/main/kotlin/com/pinterest/ktlint/Main.kt
-> Run.
Whenever a commit is added to the master
branch a snapshot build is automatically uploaded to Sonatype's snapshots repository.
If you are eager to try upcoming changes (that might or might not be included in the next stable release) you can do
so by changing version of ktlint to <latest-version>-SNAPSHOT
+ adding a repo:
...
<repository>
<id>sonatype-snapshots</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</repository>
...
repositories {
maven {
url "https://oss.sonatype.org/content/repositories/snapshots"
}
}
Additionally, project publishes snapshots build against latest kotlin development version. To use them, change version
of ktlint to <latest-version>-kotlin-dev-SNAPSHOT
.
This project is not affiliated with nor endorsed by JetBrains.
All code, unless specified otherwise, is licensed under the MIT license.
Copyright (c) 2019 Pinterest, Inc.
Copyright (c) 2016-2019 Stanley Shyiko.