def fill_paragraphs(text, width=None, preserve_newlines=False): """ Wraps multiple paragraphs in text and returns them. :param text: paragraphs to be wrapped :param width: ensure that each paragraph is at most width chars long :param preserve_newlines: preserve newlines in text if True :returns: a text with wrapped paragraphs """ if width is None: # if width isn't passed then try to get value from the operating # system environment or fall to default. please note, the try # block is used because we don't want to fail in case of garbage # in the environment variable. try: width = int(os.environ['COLUMNS']) except (KeyError, ValueError): width = 70 if not preserve_newlines: return textwrap.fill(text, width) return '\n'.join(textwrap.fill(line, width) for line in text.split('\n'))