1 //===- IndentedOstream.cpp - raw ostream wrapper to indent ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // raw_ostream subclass that keeps track of indentation for textual output
10 // where indentation helps readability.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "mlir/Support/IndentedOstream.h"
15 
16 using namespace mlir;
17 
18 raw_indented_ostream &mlir::raw_indented_ostream::reindent(StringRef str) {
19   StringRef remaining = str;
20   // Find leading whitespace indent.
21   while (!remaining.empty()) {
22     auto split = remaining.split('\n');
23     size_t indent = split.first.find_first_not_of(" \t");
24     if (indent != StringRef::npos) {
25       leadingWs = indent;
26       break;
27     }
28     remaining = split.second;
29   }
30   // Print, skipping the empty lines.
31   *this << remaining;
32   leadingWs = 0;
33   return *this;
34 }
35 
36 void mlir::raw_indented_ostream::write_impl(const char *ptr, size_t size) {
37   StringRef str(ptr, size);
38   // Print out indented.
39   auto print = [this](StringRef str) {
40     if (atStartOfLine)
41       os.indent(currentIndent) << str.substr(leadingWs);
42     else
43       os << str.substr(leadingWs);
44   };
45 
46   while (!str.empty()) {
47     size_t idx = str.find('\n');
48     if (idx == StringRef::npos) {
49       if (!str.substr(leadingWs).empty()) {
50         print(str);
51         atStartOfLine = false;
52       }
53       break;
54     }
55 
56     auto split =
57         std::make_pair(str.slice(0, idx), str.slice(idx + 1, StringRef::npos));
58     // Print empty new line without spaces if line only has spaces.
59     if (!split.first.ltrim().empty())
60       print(split.first);
61     os << '\n';
62     atStartOfLine = true;
63     str = split.second;
64   }
65 }
66