From 3927df532fd4e282a2cf582bd78cf2a864412270 Mon Sep 17 00:00:00 2001
From: Grisha Levit <grishalevit@gmail.com>
Date: Thu, 13 Jul 2023 18:04:39 -0400
Subject: [PATCH 2/2] <<# indent-stripping heredoc: indented printing

print_cmd.c
- print_redirection,print_heredoc_body,print_heredoc_bodies: move
  printing of newline before heredoc body into print_heredoc_body
- print_heredoc_body_indented: new function to print <<# heredoc with
  indentation
- print_heredoc_body: call print_heredoc_body_indented if printing a <<#
  heredoc
---
 print_cmd.c | 34 ++++++++++++++++++++++++++--------
 1 file changed, 26 insertions(+), 8 deletions(-)

diff --git a/print_cmd.c b/print_cmd.c
index ac18109b..c400810a 100644
--- a/print_cmd.c
+++ b/print_cmd.c
@@ -993,12 +993,9 @@ print_heredoc_bodies (REDIRECT *heredocs)
 {
   REDIRECT *hdtail;
 
-  cprintf ("\n"); 
   for (hdtail = heredocs; hdtail; hdtail = hdtail->next)
-    {
-      print_heredoc_body (hdtail);
-      cprintf ("\n");
-    }
+    print_heredoc_body (hdtail);
+  cprintf ("\n");
   was_heredoc = 1;
 }
 
@@ -1104,11 +1101,33 @@ print_heredoc_header (REDIRECT *redirect)
     cprintf ("%s", redirect->here_doc_eof);
 }
 
+static void
+print_heredoc_body_indented (REDIRECT *redirect)
+{
+  char *copy, *cur, *next;
+
+  indentation += indentation_amount;
+
+  cur = copy = savestring (redirect->redirectee.filename->word);
+  while (cur && (next = strchr (cur, '\n')))
+    {
+      *next = '\0';
+      newline (cur);
+      cur = next + 1;
+    }
+  free (copy);
+
+  indentation -= indentation_amount;
+  newline (redirect->here_doc_eof);
+}
+
 static void
 print_heredoc_body (REDIRECT *redirect)
 {
-  /* Here doc body */
-  cprintf ("%s%s", redirect->redirectee.filename->word, redirect->here_doc_eof);
+  if (redirect->instruction == r_unindent_reading_until)
+    print_heredoc_body_indented (redirect);
+  else
+    cprintf ("\n%s%s", redirect->redirectee.filename->word, redirect->here_doc_eof);
 }
 
 static void
@@ -1173,7 +1192,6 @@ print_redirection (REDIRECT *redirect)
     case r_detab_reading_until:
     case r_unindent_reading_until:
       print_heredoc_header (redirect);
-      cprintf ("\n");
       print_heredoc_body (redirect);
       break;
 
-- 
2.41.0

