private static void removeTrailngBlankLines(@NotNull Document document, boolean keepLast) {
    if (document.getLineCount() > 0) {
      int endOffset = document.getTextLength() - 1;
      Ref<Integer> deleteToExclusive = Ref.create(endOffset + 1);
      CharSequence content = document.getCharsSequence();
      int blankAreaOffset = CharArrayUtil.shiftBackward(content, endOffset, " \t\r\n" );
      if (blankAreaOffset < endOffset) {
        final int firstNewLineOffset = CharArrayUtil.indexOf(content, "\n", blankAreaOffset);
        if (firstNewLineOffset > 0) {
          if (keepLast) {
            int lastLNewLineOffset = CharArrayUtil.lastIndexOf(content, "\n", endOffset);
            if (lastLNewLineOffset >= firstNewLineOffset) {
              deleteToExclusive.set(lastLNewLineOffset);
            }
          }
          performUndoableWrite(new DocumentRunnable(document, null) {
            @Override
            public void run() {
              document.deleteString(firstNewLineOffset, deleteToExclusive.get());
            }
          });
        }
      }
    }
  }
private static void removeTrailngBlankLines(@NotNull Document document, boolean keepLast)