1 /* 2 * Copyright (c) Meta Platforms, Inc. and affiliates. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.facebook.ktfmt.format 18 19 import java.util.regex.Pattern 20 import java.util.regex.Pattern.MULTILINE 21 22 object WhitespaceTombstones { 23 /** See [replaceTrailingWhitespaceWithTombstone]. */ 24 const val SPACE_TOMBSTONE = '\u0003' 25 Stringnull26 fun String.indexOfWhitespaceTombstone() = this.indexOf(SPACE_TOMBSTONE) 27 28 /** 29 * Google-java-format removes trailing spaces when it emits formatted code, which is a problem for 30 * multiline string literals. We trick it by replacing the last trailing space in such cases with 31 * a tombstone, a character that's unlikely to be used in a regular program. After formatting, we 32 * replace it back to a space. 33 */ 34 fun replaceTrailingWhitespaceWithTombstone(s: String): String { 35 return Pattern.compile(" ($)", MULTILINE).matcher(s).replaceAll("$SPACE_TOMBSTONE$1") 36 } 37 38 /** See [replaceTrailingWhitespaceWithTombstone]. */ replaceTombstoneWithTrailingWhitespacenull39 fun replaceTombstoneWithTrailingWhitespace(s: String): String { 40 return s.replace(SPACE_TOMBSTONE, ' ') 41 } 42 } 43