Skip to content

Commit

Permalink
Support leading whitespace in formatters (#1601)
Browse files Browse the repository at this point in the history
Fixes #616
  • Loading branch information
AndreasArvidsson authored Nov 16, 2024
1 parent cb54f25 commit d049c53
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
15 changes: 11 additions & 4 deletions core/text/formatters.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ def _title_case_words(self, words: list[str]) -> list[str]:

class CapitalizeFormatter(Formatter):
def format(self, text: str) -> str:
return re.sub(r"^\S+", lambda m: capitalize_first(m.group()), text)
return re.sub(r"^\s*\S+", lambda m: capitalize_first(m.group()), text)

def unformat(self, text: str) -> str:
return unformat_upper(text)
Expand All @@ -159,16 +159,23 @@ class SentenceFormatter(Formatter):
def format(self, text: str) -> str:
"""Capitalize first word if it's already all lower case"""
words = [x for x in re.split(r"(\s+)", text) if x]
if words and words[0].islower():
words[0] = words[0].capitalize()
for i in range(len(words)):
word = words[i]
if word.isspace():
continue
if word.islower():
words[i] = word.capitalize()
break
return "".join(words)

def unformat(self, text: str) -> str:
return unformat_upper(text)


def capitalize_first(text: str) -> str:
return text[:1].upper() + text[1:]
stripped = text.lstrip()
prefix = text[: len(text) - len(stripped)]
return prefix + stripped[:1].upper() + stripped[1:]


def capitalize(text: str) -> str:
Expand Down
16 changes: 16 additions & 0 deletions test/test_formatters.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ def test_capitalize():

assert result == "Hello world"

result = formatters.Actions.formatted_text(" hello world", "CAPITALIZE")

assert result == " Hello world"

result = formatters.Actions.formatted_text("hEllo wOrld", "CAPITALIZE")

assert result == "HEllo wOrld"
Expand All @@ -37,6 +41,12 @@ def test_capitalize_first_word():

assert result == "Hello world"

result = formatters.Actions.formatted_text(
" hello world", "CAPITALIZE_FIRST_WORD"
)

assert result == " Hello world"

result = formatters.Actions.formatted_text(
"hEllo wOrld", "CAPITALIZE_FIRST_WORD"
)
Expand All @@ -50,6 +60,12 @@ def test_capitalize_all_words():

assert result == "Hello World"

result = formatters.Actions.formatted_text(
" hello world", "CAPITALIZE_ALL_WORDS"
)

assert result == " Hello World"

result = formatters.Actions.formatted_text(
"hEllo wOrld", "CAPITALIZE_ALL_WORDS"
)
Expand Down

0 comments on commit d049c53

Please sign in to comment.