diff --git a/titlecase/__init__.py b/titlecase/__init__.py index fd24431..f521feb 100755 --- a/titlecase/__init__.py +++ b/titlecase/__init__.py @@ -82,7 +82,7 @@ def titlecase(text, callback=None, small_first_last=True, preserve_blank_lines=F :param text: Titlecases input text :param callback: Callback function that returns the titlecase version of a specific word :param small_first_last: Capitalize small words (e.g. 'A') at the beginning; disabled when recursing - :param preserve_blank_lines: Preserve blank lines in the output + :param preserve_blank_lines: Preserve blank lines and original line endings in the output :param normalise_space_characters: Convert all original spaces to normal space characters :type text: str :type callback: function @@ -98,7 +98,9 @@ def titlecase(text, callback=None, small_first_last=True, preserve_blank_lines=F """ if preserve_blank_lines: - lines = regex.split('[\r\n]', text) + lines = regex.split(r'(\r\n|\r|\n)', text) + line_endings = iter(lines[1::2]) + lines = lines[::2] else: lines = regex.split('[\r\n]+', text) processed = [] @@ -207,9 +209,11 @@ def titlecase(text, callback=None, small_first_last=True, preserve_blank_lines=F m.group(2).capitalize() ), result) + if preserve_blank_lines: + result += next(line_endings, '') processed.append(result) - result = "\n".join(processed) + result = ("" if preserve_blank_lines else "\n").join(processed) logger.debug(result) return result diff --git a/titlecase/tests.py b/titlecase/tests.py index 9265ec0..651d232 100644 --- a/titlecase/tests.py +++ b/titlecase/tests.py @@ -421,6 +421,27 @@ class TestBlankLines(unittest.TestCase): # but that's what it was from day one, so we're kind of stuck with that. # This ensures folks can opt-out of that behavior if they want. + def test_preserves_line_endings(self): + for newline in ('\n', '\r\n', '\r'): + for blanks in (1, 2, 3): + with self.subTest(newline=newline, blanks=blanks): + source = newline + 'one line' + newline * blanks + 'and another' + newline + expected = newline + 'One Line' + newline * blanks + 'And Another' + newline + self.assertEqual(titlecase(source, preserve_blank_lines=True), expected) + + def test_preserves_mixed_line_endings(self): + self.assertEqual( + titlecase('one\r\n\ntwo\rthree\n', preserve_blank_lines=True), + 'One\r\n\nTwo\rThree\n') + + def test_empty_input_and_line_endings_only(self): + for source in ('', '\r\n', '\r\n\r\n', '\r\n\n\r'): + with self.subTest(source=source): + self.assertEqual(titlecase(source, preserve_blank_lines=True), source) + + def test_default_still_collapses_blank_lines(self): + self.assertEqual(titlecase('one\r\n\r\ntwo\rthree\n'), 'One\nTwo\nThree\n') + def test_one_blank(self): s = 'Line number one\n\nand Line three\n' self.assertEqual(titlecase(s), 'Line Number One\nAnd Line Three\n')