Search code examples
android-studiointellij-ideacode-inspectioninspectionstructural-search

How to eliminate 'braces on new line' using Intellij search and replace pattern?


I'm trying to find all if statements where the curly brackets are written in a new line using the following search and replace template:

Search template:

if ($Expr$)
{
    $ThenStatements$;
}
else
{
    $ElseStatements$;
}

Replace template:

if ($Expr$) {
    $ThenStatements$;
}
else {
    $ElseStatements$;
}

The problem i'm facing if that the template engine does not differentiate between both templates. It offers me to replace the search template with the correct one, but it also detects 'correct' templates as faulty ones.

Is there a way around this using some kind of regex?

Edit: Working on Android Studio. I'm trying to generate a set of lint rules for my companies Code Styling conventions which will appear as warnings or errors


Solution

  • Structural Search & Replace is designed for searching code no matter how it's formatted. Therefore your usecase is not really supported. However with a bit of a hack it is possible to get what you want out of it.

    Start with your search template and add the following Groovy script constraints to the $Expr$ variable:

    import com.intellij.psi.*
    import com.intellij.openapi.editor.Document
    
    PsiDocumentManager dm = PsiDocumentManager.getInstance(__context__.project)
    Document d = dm.getDocument(__context__.containingFile)
    PsiIfStatement is = __context__.parent
    if (is.thenBranch != null && is.thenBranch.text.startsWith("{")) {
      if (d.getLineNumber(is.thenBranch.textOffset) > d.getLineNumber(is.RParenth.textOffset))
        return true
    }
    if (is.elseBranch != null && is.elseBranch.text.startsWith("{")) {
      if (d.getLineNumber(is.elseBranch.textOffset) > d.getLineNumber(is.elseElement.textOffset))
        return true;
    }
    return false 
    

    This script checks if the then branch { is on a line greater than the ) of the if statement, or if the else branch { is on a line greater than the else keyword, or returns false otherwise.