1 /*
2 * Copyright 2018 Google LLC
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 * https://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 org.jetbrains.dokka.Utilities
18
19 /**
20 * Finds the first sentence of a string, accounting for periods that may occur in parenthesis.
21 */
firstSentencenull22 fun String.firstSentence(): String {
23
24 // First, search for location of first period and first parenthesis.
25 val firstPeriodIndex = this.indexOf('.')
26 val openParenIndex = this.indexOf('(')
27
28 // If there is no opening parenthesis found or if it occurs after the occurrence of the first period, just return
29 // the first sentence, or the entire string if no period is found.
30 if (openParenIndex == -1 || openParenIndex > firstPeriodIndex) {
31 return if (firstPeriodIndex != -1) {
32 this.substring(0, firstPeriodIndex + 1)
33 } else {
34 this
35 }
36 }
37
38 // At this point we know that the opening parenthesis occurs before the first period, so we look for the matching
39 // closing parenthesis.
40 val closeParenIndex = this.indexOf(')', openParenIndex)
41
42 // If a matching closing parenthesis is found, take that substring and recursively process the rest of the string.
43 // This is to accommodate periods inside of parenthesis. If a matching closing parenthesis is not found, return the
44 // original string.
45 return if (closeParenIndex != -1) {
46 this.substring(0, closeParenIndex) + this.substring(closeParenIndex, this.length).firstSentence()
47 } else {
48 this
49 }
50
51 }