Create a codeblock tool

18

1

When using Markup, like on the SE network, an indentation of four spaces before a line of text denotes it as part of a code block, as I hope you know. If you don't, here's an example (with . representing a space):

....Code
....More code

results in

Code
More code

The problem is, when you copy-paste code into an answer, you need to indent each line manually. This is especially difficult when working with ungolfed code, as it's likely already indented and can cause confusion. You can just select your code and hit Ctrl + K, it turns out. Hours of my life wasted for no reason aside...

So, your goal is, given an input, return it with four spaces before each line. In the spirit of saving time copy-pasting, you are to process the entire input as a single string (so long as your language can parse it). If your language is unable to process a character (such as newlines) in strings, you may assume it is denoted/escaped through some other method supported by the language; however, the output must output each line on its own line (so no passing something like ....foo\n....bar).

Standard loopholes not allowed. As this is , the shortest answer in bytes wins. Good luck!

Papayaman1000

Posted 2017-04-08T19:24:47.833

Reputation: 603

3"you need to indent each line manually" (or select the text and click the button :)) – Jonathan Allan – 2017-04-08T19:29:00.547

11@JonathanAllan "Button"? Surely you mean "keyboard shortcut". (Ctrl+K) – Martin Ender – 2017-04-08T19:29:59.730

31@JonathanAllan ...I... I am very upset. SO MUCH TIME. WASTED. – Papayaman1000 – 2017-04-08T19:31:31.607

I find mashing my big trackpad easier than finding two keys, but hey each to their own – Jonathan Allan – 2017-04-08T19:31:46.293

Must the output be printed, or is a list of strings acceptable? – Greg Martin – 2017-04-08T19:38:37.593

@GregMartin It can be output however you like, but said output must be copy-pastable without altering the input (wrappers aside). In other words, so long as it's identical to just using Ctrl + K, go for it. – Papayaman1000 – 2017-04-08T19:40:41.870

6While I'm fairly confident that Kritixi's V answer won't be beaten, I would typically recommend waiting a bit longer before accepting an answer, because accepting so early poses a disadvantage to people who could answer with a shorter answer but weren't on the site at the time (timezones or just not always being on PPCG 24/7) – HyperNeutrino – 2017-04-08T20:12:00.363

@HyperNeutrino Right. I did take that into account, but...

I mean, 6 bytes?! I'm pretty sure even some HQ9+ answers use more. [In the meantime, though, I'll wait until they at least change the bytecount to reflect Unicode as well.] – Papayaman1000 – 2017-04-08T20:13:12.160

It's 4 now, so it's probably not going to be beaten, but you never know. – HyperNeutrino – 2017-04-08T20:13:42.503

you are to process the entire input as a single string Do you mean that the program must accept the input as a whole but can get it char-by-char or line-by-line or anything or that the program must actually load the whole input in memory at once before processing it? – Erik the Outgolfer – 2017-04-09T09:27:57.567

2+1 for informing people about Ctrl + K – Koishore Roy – 2017-04-09T09:54:43.267

So is it kay with tab spacing. Without ctrl+k is nothing but a tab! – Keerthana Prabhakaran – 2017-04-09T13:29:50.947

@KoishoreRoy Thank Johnathan Allan and Martin Ender. I had no clue (hence the strikethrough [which apparently doesn't work in comments, no matter which method you try]). – Papayaman1000 – 2017-04-09T18:23:13.603

I prefer to copy a tab and paste it in front of each line, unless my code is long. – mbomb007 – 2017-04-12T16:09:23.077

@HyperNeutrino If they aren't on PPCG 24/7, they don't deserve to win :P – Esolanging Fruit – 2017-04-14T22:51:45.753

Puzzle still valid if you want to insert code after a list item.

– Draco18s no longer trusts SE – 2017-04-26T03:16:39.203

@Papayaman1000 wh... WHAT THE $@#* I'M ANGRY AS HELL TOO. – Magic Octopus Urn – 2017-05-09T19:40:58.567

Answers

17

V, 4 bytes

Î4É 

Try it online!

(Note the trailing space)

V is encoded in Latin1, where this is encoded like so:

00000000: ce34 c920                                .4. 

Explanation

Î            " On every line
 4É<space>   " Prepend 4 spaces

Here's a solution that is also 4 bytes in UTF-8!

VG4>

VG          " Select everything
   >        " Indent
  4         " 4 times (with spaces)

user41805

Posted 2017-04-08T19:24:47.833

Reputation: 16 320

2Hope somebody picks up that phone, cause wow did someone call it. – Papayaman1000 – 2017-04-08T19:45:56.007

Alternate solution: 4ñ>G – James – 2017-04-08T20:07:56.067

@DJMcMayhem But it uses tabs to indent instead of spaces – user41805 – 2017-04-08T20:09:48.240

In vim, yes. In V, no, it's 4 spaces – James – 2017-04-08T20:10:34.060

@DJMcMayhem Thanks, that inspired another alternative solution that is only 4 bytes in UTF-8! – user41805 – 2017-04-08T20:17:59.337

Couldn't VG> work assuming softtabs and tab length = 4 is set? – Downgoat – 2017-04-08T23:28:12.450

@Downgoat Probably, but vim-golf assumes that .vimrc is not loaded, so that you cannot have special mappings for certain keystrokes or what you said by modifying the default settings – user41805 – 2017-04-09T07:51:33.317

9

Crayon, 7 bytes

`¤q;3xq

Try it online!

Explanation

Crayon is a stack-based language designed for creating ASCII-art. It's still in the early stages of development, but it knows just enough to finish this challenge with a rather low byte count:

         Implicit: input string is on the stack
`¤       Push a non-breaking space to the stack.
  q;     Draw this at the cursor (0,0 by default) and pop it.
    3x   Move three more spaces to the right.
      q  Draw the input string here (at 4,0).
         Implicit: output the canvas, trimmed to a rectangle

Drawing the non-breaking space is necessary because Crayon automatically trims the output to a rectangle, so without the NBSP it would just print the original input.

ETHproductions

Posted 2017-04-08T19:24:47.833

Reputation: 47 880

Would Crayon let you do the opposite: output the string, then move four spaces to the left and output a nbsp? That's likely to cost less in stack manipulation, although I don't know whether Crayon would correctly move the canvas into the right place. – None – 2017-04-09T13:26:43.067

@ais523 Hmm, that's a really good idea... unfortunately, that'd require moving to x=-4, which is not an easy task at the moment. I really should push these changes I've been working on for a month... :P – ETHproductions – 2017-04-09T18:50:30.420

7

Retina, 8 bytes

%`^

Try it online!

There are four spaces on the second line. Alternative solutions use either m`^ or %1` or 1%` on the first line. All of these match the position at the beginning of each line and replace it with four spaces.

Martin Ender

Posted 2017-04-08T19:24:47.833

Reputation: 184 808

I suspected a Retina answer would be first. – Neil – 2017-04-08T19:31:47.180

Well that was fast. – Papayaman1000 – 2017-04-08T19:32:34.580

@Neil I'll be surprised if this doesn't get beaten by V (or even raw Vim). :) – Martin Ender – 2017-04-08T19:32:48.007

1

@MartinEnder Here ya go (4 bytes in V): http://codegolf.stackexchange.com/a/115870/41805 :)

– user41805 – 2017-04-08T19:44:22.317

7

Cheddar, 31 bytes

@.lines.map(("    ":+)).asLines

Really simply, but I posted because it shows off the new functional operators.

(" ":+) is the same as A -> " " + A. (i.e. + op as a function with " " bound to LHS).

I don't think even needs explanation

Downgoat

Posted 2017-04-08T19:24:47.833

Reputation: 27 116

Oh did you change how the parser works? From what I remember : would cause problems with ?: – Conor O'Brien – 2017-04-08T20:17:39.447

@ConorO'Brien I kinda forgot how I fixed it but I believe that because there's a : with no matching ?, the parser will choose to treat it as a functional op. This still requires the functional op to be wrapped in parens but yeah – Downgoat – 2017-04-08T20:20:19.863

+1 for smiley :+) – LarsW – 2017-04-08T23:17:12.250

What does @ mean? – Leaky Nun – 2017-04-27T10:10:26.193

6

Python,  44  39 bytes

Crossed out &nbsp;44&nbsp; is no longer 44 :)

-5 bytes thanks to ovs (avoid dequeue with a prepend)

lambda s:' '*4+s.replace('\n','\n    ')

Try it online!

Jonathan Allan

Posted 2017-04-08T19:24:47.833

Reputation: 67 804

lambda s:' '*4+s.replace('\n','\n ') for 39 bytes – ovs – 2017-04-08T20:12:09.487

@ovs - I don't see it... do you mean lambda s:' '*4+s.replace('\n','\n ')[1:] for 40 (which does not work) or something else? – Jonathan Allan – 2017-04-08T20:16:02.500

1

Just lambda s:' '*4+s.replace('\n','\n<4 spaces>') TIO

– ovs – 2017-04-08T20:28:05.350

@ovs Ah yes, of course (the comment four space markdown rendering threw me and I didn't notice it in my reply either) thanks for the saving! – Jonathan Allan – 2017-04-08T20:30:13.707

6

JavaScript, 26 bytes

Thanks @Conor O'Brien for golfing off 8 bytes

x=>x.replace(/^/gm,"    ")

Replace with a regex with /g replaces all instances. m makes the regex treat each line separately for the start of the string ^.

Try it online!

fəˈnɛtɪk

Posted 2017-04-08T19:24:47.833

Reputation: 4 166

It seems to jumble non-whitespace in the input into asdf repeated over and over. – Papayaman1000 – 2017-04-08T20:16:42.540

You should note what I had put as the input in TIO – fəˈnɛtɪk – 2017-04-08T20:17:46.180

You can save a few bytes by doing x=>x.replace(/^|\n/g,"$&    ") to get the first line and the following lines all in one go – ETHproductions – 2017-04-08T20:18:52.747

Ah. The footer. – Papayaman1000 – 2017-04-08T20:19:12.203

1

26 bytes: Try it online!

– Conor O'Brien – 2017-04-08T20:19:33.660

1Or ^ works too I guess ;-) – ETHproductions – 2017-04-08T20:20:04.127

4

Jelly, 8 bytes

Ỵṭ€⁶ẋ4¤Y

Try it online!

How?

Ỵṭ€⁶ẋ4¤Y - Main link: string
Ỵ        - split on newlines
      ¤  - nilad followed by ink(s) as a nilad:
   ⁶     -     a space character
    ẋ4   -     repeated four times
 ṭ€      - tack for €ach
       Y - join with newlines

Some other 8 byte variants are:
Ỵṭ€⁶Yµ4¡ (4 repeats of split on newlines, tack a single space);
⁶ḤḤ;ЀỴY (doubling twice is like multiplying by 4, Ѐ maps over the right argument, so we can concatenate instead of tacking);
and other rearrangements thereof.

Jonathan Allan

Posted 2017-04-08T19:24:47.833

Reputation: 67 804

4

Python 2, 87 45 bytes

print' '*4+'\n    '.join(input().split('\n'))

Input is taken as 'Line1\nLine2\nLine3...' (Quotes necessary)

Thanks to @WheatWizard for giving me an idea that helped me golf 42 bytes.

HyperNeutrino

Posted 2017-04-08T19:24:47.833

Reputation: 26 575

I grew up on python. That's what made me think this would be sort of hard. Even ignoring RegEx, I was so wrong, turns out. – Papayaman1000 – 2017-04-08T19:44:58.877

@Papayaman1000 It's a fairly trivial challenge, both with and without RegEx, though I find it to be very interesting. – HyperNeutrino – 2017-04-08T19:45:57.187

2I will admit, since I didn't know about Ctrl + K, the real reasons for this challenge being proposed were... less than for just pure puzzling. – Papayaman1000 – 2017-04-08T19:47:25.870

@Papayaman1000 Haha, yes, it was quite annoying having to press space 4 times in front of each line. Especially since I usually use Python and so I have multiple lines all the time (it's not so bad when I used to use Java). Eventually I just got lazy and used my text editor to replace ^ with . – HyperNeutrino – 2017-04-08T19:49:06.240

Why don't you join along ' \n' instead of all of the extra nonsense? – Post Rock Garf Hunter – 2017-04-08T19:50:05.193

@HyperNeutrino Let's continue this in chat, shall we?

– Papayaman1000 – 2017-04-08T19:50:24.860

It saves 48 bytes, tio.

– Post Rock Garf Hunter – 2017-04-08T19:52:52.457

@WheatWizard Thanks, but that doesn't work. It has the spaces at the end. – HyperNeutrino – 2017-04-08T19:56:09.720

umm...why am I getting a downvote here? This doesn't appear to be invalid... – HyperNeutrino – 2017-04-08T19:57:34.923

Thats because I added an extra \n I was testing if it worked for an empty line. – Post Rock Garf Hunter – 2017-04-08T19:57:44.367

1@WheatWizard Thanks for the suggestion, I golfed it down a bit. Is it a bit better now? – HyperNeutrino – 2017-04-08T19:58:38.563

4

Emacs, 5 keychords, 5 bytes

C-x h M-4 C-x tab

In at least one commonly used encoding for keyboard entry, each of these keychords is a single byte: 18 68 b4 18 09. Emacs entries tend to be very keychord-heavy, as each printable ASCII character stands for itself except as a subsequent character of a multi-character command (meaning that only keychords can be used to give actual commands).

I'm not sure how this compares to Vim (as opposed to V). But Vim is fairly commonly used on PPCG, and so I thought the other side of the editor wars deserves its time in the spotlight too.

This assumes that I/O is done via the buffer (the equivalent of the normal I/O conventions for vim), or taken from a file and output onto the screen (which comes to the same thing). If you do I/O via the region instead, which is natural for some forms of program, you can remove the leading two characters, for a score of 3 bytes; however, I don't think that complies with PPCG rules.

Explanation

C-x h M-4 C-x tab
C-x h               Specify the entire buffer as the region
      M-4           Give the argument 4 to the next command that runs
          C-x tab   Increase the indentation level of each line by a constant

The last builtin used here is, of course, incredibly useful for this challenge; the rest is just structure.

user62131

Posted 2017-04-08T19:24:47.833

Reputation:

3

PowerShell, 29 28 Bytes

"$args"-split"
"|%{" "*4+$_}

-1 Thanks to fergusq, using an actual newline instead of the `n

takes the "$args" input as a string (cast using "s) and -splits it on a newline, then loops (%{}) through it, appending four spaces (" "*4) and the line ($_) then outputs it implicitly.

colsw

Posted 2017-04-08T19:24:47.833

Reputation: 3 195

Can you use a newline character instead of `n? – fergusq – 2017-04-08T20:02:19.640

@fergusq indeed I can, updated. – colsw – 2017-04-08T20:27:39.327

Presumably the newline character is \r\n on windows which is still two bytes - or are there rules clarifying how many bytes a newline character takes? – poizan42 – 2017-04-10T01:58:57.227

@poizan42 I'm not sure if there's a meta post on it, but I can run this in the default console with just the newline so there's no reason to consider it invalid. – colsw – 2017-04-10T08:42:23.823

3

Pyth, 10 Bytes

jm+*4\ d.z

Try it!

If input as a list of lines would be allowed, I could do it in 7 bytes:

jm+*4\ 

Try that

longer solutions:

12 Bytes:

+*4d:Eb+b*4d

12 Bytes:

+*4dj+b*4d.z

13 Bytes:

t:E"^|
"+b*4d

KarlKastor

Posted 2017-04-08T19:24:47.833

Reputation: 2 352

Got it down to 9: jbm*4\ .z – clap – 2017-05-09T00:43:11.833

@ConfusedMr_C That just overwrites every line with 4 spaces.

– KarlKastor – 2017-05-09T19:11:08.343

I forgot the d, whoops. Your 10 byte answer is what I was going for, anyway – clap – 2017-05-14T20:59:33.660

2

Röda, 21 bytes

{(_/"
")|[`    $_
`]}

Try it online!

It is an anonymous function. The input is pulled from the stream.

Explanation:

{
    (_/"\n") |        /* Splits the input at newlines */
    ["    ".._.."\n"] /* For each line, prints four spaces before the line */
}

fergusq

Posted 2017-04-08T19:24:47.833

Reputation: 4 867

Does identity() just pull all values from STDIN? – user41805 – 2017-04-08T19:57:40.113

@KritixiLithos Yes. identity pulls values from the input stream and pushes them to its output stream. It is identical to push(x) for x. – fergusq – 2017-04-08T20:01:59.283

2

Perl 5, 11+1 = 12 bytes

11 bytes of code + -p flag.

s/^/    /mg

Try it online!

For once, explanations will be short: The regex replaces each beginning of line (^ combined with /m modifier) by four spaces - the end.

Dada

Posted 2017-04-08T19:24:47.833

Reputation: 8 279

This reads input a line at a time, rather than a string as a whole. – None – 2017-04-09T02:21:16.397

@ais523 Roughly half of the answers, including the top two, read input in the exact same way. – Maxim Mikhaylov – 2017-04-09T03:39:47.317

@ais523 I'd say it processes the input one line at a time, but it can read it as a whole string (if you supply it with <<< "..." for instance). Don't you agree? – Dada – 2017-04-09T08:21:55.737

@ais523 after thinking a bit more about it, I think you're right. (I've update my code accordingly) – Dada – 2017-04-09T08:40:51.547

2

sed, 16 10 9 bytes

s/^/    /

Try it online!

Edits

Reduced solution size from 16 to 10 bytes thanks to Kritixi Lithos.

-1 byte thanks to seshoumara.

Maxim Mikhaylov

Posted 2017-04-08T19:24:47.833

Reputation: 571

You can get to 15 bytes by using the -r flag (1 byte) so that you can remove the backslashes before the parentheses. – user41805 – 2017-04-09T07:52:42.910

You can get to 13 by using s/.*/ &/ (remove the parentheses and replace \1 with &) – user41805 – 2017-04-09T07:54:04.217

@KritixiLithos Thanks! It works even without *. – Maxim Mikhaylov – 2017-04-09T12:23:34.393

Or simply s:^: :, for 9 bytes. – seshoumara – 2017-04-09T17:53:19.470

@seshoumara I've never seen colons used this way in a sed script... Do you know which part of the manual describes this syntax? – Maxim Mikhaylov – 2017-04-09T18:37:31.887

It's a habit of mine, so the code can be of course s/^/ / also. You can use other character besides /, as described here. I ended up using colons so I don't have to escape a literal '/'.

– seshoumara – 2017-04-09T18:51:54.857

@seshoumara Thanks for the tip! Didn't know that it's possible to use any other character as a separator. – Maxim Mikhaylov – 2017-04-09T19:01:39.497

For many more tips and discussions about sed, and bash in general, pass by the bash, sed and dc chat room, if interested.

– seshoumara – 2017-04-09T19:22:30.777

2

Perl 6, 11 bytes

*.indent(4)

Try it

Expanded:

*\       # declare a WhateverCode lambda/closure (this is the parameter)
.indent( # call the `indent` method on the argument
  4      # with the number 4
)

Brad Gilbert b2gills

Posted 2017-04-08T19:24:47.833

Reputation: 12 713

2

Java 7, 58 bytes

String c(String s){return"    "+s.replace("\n","\n    ");}

Explanation:

Try it here.

  • Append with four leading spaces
  • Replace every new-line for a new-line + four spaces

Kevin Cruijssen

Posted 2017-04-08T19:24:47.833

Reputation: 67 575

I am forever sad that Java's regex mechanisms require other libraries for the most part. – Poke – 2017-04-10T17:30:34.537

I think you need replaceAll – Khaled.K – 2017-05-09T09:36:45.397

@Khaled.K Why? Both .replace and .replaceAll will replace all occurrences of the searched String with the replacement. .replace is used for literal Strings, and .replaceAll for regexes. Since \n isn't a regex, .replace can be used without a problem to replace all newlines with a newline + four spaces, which you can also check in the "Try it line" link I provided. – Kevin Cruijssen – 2017-05-09T11:31:03.977

2

Brain-Flak, 109 103 bytes

-6 thanks to Wheat Wizard

Includes +1 for -c

((()()()()()){}){(({}<>)[()()((()()()()){})]<(((((({}){}){}))))>){(<{}{}{}{}{}>)}{}<>}<>{({}<>)<>}<>{}

Try it online!

((()()()()()){})        # Add a newline to the beginning
                        # This is needed to get spaces infront of the first line)
{                       # For every character (call it C)
  (({}<>)               #   Move C to the other stack
  [()()((()()()()){})]  #   Push 8 and subtract 10 (\n) from C
  <(((((({}){}){}))))>) #   Push 4 spaces using the 8 from earlier
  )                     #   Push C - 10
  {(<                   #   If C - 10 != 0...
    {}{}{}{}{}          #     Pop the 4 spaces that we added
  >)}{}                 #   End if
  <>                    #   Switch stacks to get the next character
}                       # End while
<>{({}<>)<>}<>          # Reverse the stack (back to the original order)
{}                      # Pop the newline that we added

Riley

Posted 2017-04-08T19:24:47.833

Reputation: 11 345

Moved some stuff around saved some bytes – Post Rock Garf Hunter – 2017-04-14T19:48:10.337

... and two more bytes off – Post Rock Garf Hunter – 2017-04-14T19:58:33.813

@WheatWizard Nice. I need to start looking for redundancies like that. It probably happens to me more than push pop does. Those are just automatic now. Thanks – Riley – 2017-04-14T20:05:11.037

1

PHP, 43 Bytes

<?="    ".strtr($_GET[0],["\n"=>"\n    "]);

Jörg Hülsermann

Posted 2017-04-08T19:24:47.833

Reputation: 13 026

1

Stacked, 13 bytes

'^'4' '*mrepl

Try it online!

Explanation

'^'4' '*mrepl      (* input: top of stack *)
        mrepl      perform multiline regex replacements,
'^'                  replacing /^/ with
   4' '*             four spaces

Conor O'Brien

Posted 2017-04-08T19:24:47.833

Reputation: 36 228

1

05AB1E, 7 5 bytes

Saved 2 bytes thanks to kalsowerus

¶¡4ú»

Try it online!

Explanation

¶¡        # split input on newline
  4ú      # prepend 4 spaces to each
    »     # join by newline

Emigna

Posted 2017-04-08T19:24:47.833

Reputation: 50 798

You can use | instead of ¶¡. https://tio.run/nexus/05ab1e#@19zeIPJ4emH1xza/f9/Uk4iFxAjKCACAA

– Okx – 2017-04-09T09:04:56.697

@Okx: Unfortunately not, as the input had to be one string and not several inputs separated by newlines :( – Emigna – 2017-04-09T09:10:36.627

Maybe a little late, but ð4×ì could be replaced by , does the exact same thing. Assuming that command was available back then. – kalsowerus – 2017-05-15T13:11:46.477

@kalsowerus: The command was indeed available back then. Thanks :) – Emigna – 2017-05-15T13:47:22.510

1

MATL, 12 bytes

10&Yb"4Z"@gh

Input is a string with newlines. To enter this, you need to concatenate character 10 between the normal characters to represent newline (square brackets are concatenattion):

['Code' 10 'More code']

Try it at MATL online!

Explanation

10&Yb   % Implicit input. Split at char 10 (newline). Gives cell array of strings
"       % For each
  4Z"   %   Push string of 4 spaces
  @g    %   Push the contents of current cell array, i.e. a string with one of the
        %   original lines
  h     %   Concatenate the two strings horizontally
        % Implicit end. Implicit display

Luis Mendo

Posted 2017-04-08T19:24:47.833

Reputation: 87 464

1

CJam, 11 bytes

Thanks to @Challenger5 for a correction

qN/{S4*\N}%

Try it online!

Explanation

q              e#  Read whole input as a string with newlines
 N/            e#  Split at newlines, keeping empty pieces. Gives an array of strings
   {     }%    e#  Map this function over the array of strings
               e#  The current string is automatically pushed
    S4*        e#  Push a string of four spaces
       \       e#  Swap. Moves the original string after the four spaces
        N      e#  Push a newline
               e#  Implicity display stack contents

Luis Mendo

Posted 2017-04-08T19:24:47.833

Reputation: 87 464

1Doesn't work on abc\n\ndef. It returns ....abc\n....def because % discards empty elements. You want to use / to split instead, because it keeps the empty elements. – Esolanging Fruit – 2017-05-09T01:40:54.523

@Challenger5 Thanks, corrected! – Luis Mendo – 2017-05-09T07:39:24.500

1

Octave, 17 bytes

@(s)["    "';s']'

Try it online!

rahnema1

Posted 2017-04-08T19:24:47.833

Reputation: 5 435

1

C, 66 65 bytes

p(){printf("    ");}f(char*s){for(p();*s;)putchar(*s++)-10||p();}

Try it online!

Steadybox

Posted 2017-04-08T19:24:47.833

Reputation: 15 798

Neat solution, but you could go with s;char*l;f(){while(getline(&l,&s,stdin)+1)printf("____%s",l);} which 62 bytes – Khaled.K – 2017-05-09T09:48:37.163

@Khaled.K Thanks, but that doesn't seem to work without including <stdio.h> (because of the stdin). – Steadybox – 2017-05-09T10:06:45.840

1

Vim, 6 keystrokes

<Ctrl-V>G4I <Esc>

Assumes that the cursor is on the beginning of the file, as if you opened the file from from the command line via vim filename.

<Ctrl-V>            " Enter visual block move (enables rectangular selection)
        G           " Move to bottom line (selecting the entire first column)
         4          " Repeat the following action 4 times
          I         " Insert at start of (each selected) line
                    " [input a space]
            <Esc>   " Exit insert mode

With a vim configured to use 4 spaces for indentation it would be 2 keystrokes: >G.

daniero

Posted 2017-04-08T19:24:47.833

Reputation: 17 193

I'm pretty sure you can remove the ZZ at the end. Usually vim submissions are fine just outputting to the buffer rather than to a file. – James – 2017-04-10T17:14:14.693

Alright thanks, I removed ZZ then. – daniero – 2017-04-11T17:53:05.487

1

PHP, 16

echo"    $argn";

run with php -R <code>. -R runs the given code for every input line and $argn is fed the current input line. So this simply prints each line with additional four spaces in front of it.

Christoph

Posted 2017-04-08T19:24:47.833

Reputation: 1 489

1

V, 3 bytes (Non-competing)

4>G

This is answer uses a feature that I have been planning on adding for a while, but just got around to adding today. That makes this answer non-competing and invalid for winning. But it's still cool to show off such a useful/competitive feature!

Try it online!

Explanation:

4>   " Add an indent of 4 to...
  G  "   Every line from the current line (0 by default) to the end of the buffer

James

Posted 2017-04-08T19:24:47.833

Reputation: 54 537

Neat! At least take some pride in the fact that your language took the top spot even beforehand [even if it is a dirty golfing language... nah, jk]! – Papayaman1000 – 2017-04-11T01:10:12.723

1

Japt, 7 6 bytes

Saved 1 byte thanks to @ETHproductions

miS²²R

Try it online!

Explanation:

miS²²R
m       // At each char in the input:
 iS²²   //   Prepend " " repeated 4 times
     R  // Rejoin with newlines  

Oliver

Posted 2017-04-08T19:24:47.833

Reputation: 7 160

Nice job. S²² would work as well in place of Sp4, not that it saves you anything in this case. Speaking of which, I think you can just do miS²²R to remove the R flag (basically miS²², but split at newlines beforehand and join with newlines afterward) – ETHproductions – 2017-04-15T14:49:22.013

1

UberGenes, 62 bytes

I had to enter this challenge with UberGenes, as a very similar program (that only inserted one space) was one of the first programs I ever wrote in the language, and it seemed like it would be easy to modify for this purpose.

=aA=p9=z4=cI=AC+a1-z1:pz=Ao:CA:Ii  =b5+b5-bA+a1=d3*d7:db=i0   

How it works:

=aA                                                         Set a to 61
                                                            (Begin main loop)
   =p9                                                      Set p to 9
      =z4                                                   z counts spaces
         =cI                                                Set c to 61
                                                            (Jumping to p jumps here)
            =AC                                             Put the space at position 61
                                                              at position a.
               +a1-z1                                       Move a right and decrement z
                     :pz                                    Jump to p if z is nonzero
                                                            (Jumping to d jumps here)
                        =Ao                                 Read a character to position a.
                           :CA                              Jump to position 32+3 if input
                                                              was nonzero.
                              :Ii                           Otherwise, jump to position 61,
                                                              causing the entire string
                                                              that begins there to be
                                                              printed before halting.
                                                            (This is position 32+3=35)
                                   =b5+b5                   Set b to 10 (newline).
                                         -bA                Subtract the input character to
                                                              compare it with newline.
                                            +a1             Move a right.
                                               =d3*d7       Set d to 21
                                                     :db    Jump to d if not newline.
                                                        =i0 Jump back to begin main loop.
(The 3 spaces at the end position a space character at position 61 so that, after =cI,
C refers to the space character--it will also be the first space printed.)

quintopia

Posted 2017-04-08T19:24:47.833

Reputation: 3 899

1

J-uby, 17 16 Bytes

~:gsub&' '*4&/^/

Explanation

~:gsub           # :gsub with reversed arguments: 
                 # (f)[regex,sub,str] == str.gsub(regex, sub)
      &' '*4     # replace with four spaces
            &/^/ # match the start of each line

This directly translates to (in Ruby):

->s{s.gsub(/^/,' '*4)}

Cyoce

Posted 2017-04-08T19:24:47.833

Reputation: 2 690

1

Ruby, 22 21 Bytes

1 Byte saved thanks to @manatwork

->s{s.gsub /^/,' '*4}

Takes s, replaces all occurences of /^/ (start of line) with four spaces.

Cyoce

Posted 2017-04-08T19:24:47.833

Reputation: 2 690

' '*4 is 1 character shorter. – manatwork – 2017-05-09T20:03:08.697

1

Actually, 16 bytes

9uc;§s⌠' 4*+⌡M@j

Try it online!

Explanation:

9uc;§s⌠' 4*+⌡M@j
9uc;              push two newlines
    §s            raw input, split on newlines
      ⌠' 4*+⌡M    for each line:
       ' 4*+        prepend 4 spaces
              @j  join with newlines

Mego

Posted 2017-04-08T19:24:47.833

Reputation: 32 998

0

Swift, 94 bytes

func f(g:String){print(g.components(separatedBy:"\n").map{"    "+$0}.reduce("",{$0+"\n"+$1}))}

This is a function, that can be used like this:

f(g:"YOUR\nSTRING") 

Mr. Xcoder

Posted 2017-04-08T19:24:47.833

Reputation: 39 774

3Y'know for people golfing from their iPads. – Papayaman1000 – 2017-04-08T20:18:03.587

0

GolfScript, 14 bytes

n/{' '4*\+}%n*

Try it online!

Note: if trailing newline is disallowed, append :n; for 17 bytes.

Erik the Outgolfer

Posted 2017-04-08T19:24:47.833

Reputation: 38 134

0

brainfuck, 57 bytes

++++[>>++++++++<<-]>+<,[>[->....<]+<.----------[>-<[-]],]

Online interpreter

You need to use \n for newlines, although they get parsed as actual newlines (input field at the bottom).

Set EOF = \0 (go to Options > End of input > char = \0).

Erik the Outgolfer

Posted 2017-04-08T19:24:47.833

Reputation: 38 134

I have asked OP for clarification if something like this is allowed. – Erik the Outgolfer – 2017-04-09T16:44:00.890

0

Gema, 13 characters

/.*/=\     $0

Sample run:

bash-4.3$ gema '/.*/=\     $0' <<< $'Code\nMore code'
    Code
    More code

manatwork

Posted 2017-04-08T19:24:47.833

Reputation: 17 865

0

jq, 24 characters

(19 characters code + 5 characters command line options)

(./"\n")[]|"    "+.

Sample run:

bash-4.3$ jq -sRr '(./"\n")[]|"    "+.' <<< $'Code\nMore code'
    Code
    More code

On-line test

jq, 13 characters

(8 characters code + 5 characters command line options)

If we can rely on the interpreter's line oriented processing mode.

"    "+.

bash-4.3$ jq -Rr '" "+.' <<< $'Code\nMore code' Code More code

On-line test

manatwork

Posted 2017-04-08T19:24:47.833

Reputation: 17 865

0

Common Lisp, 65 61 bytes

-4 thanks to Julian

(loop for l =(read-line t nil)while l do(format t"~4t~A~%"l))

Reads from *standard-input* (stdin, by default) and writes four spaces followed by each line to *standard-output* (stdout, by default).

Ungolfed

(loop :for l := (read-line t nil) :while l :do (format t"~4t~A~%" l))

Explanation

(read-line t nil)

Read a line from *standard-input* (shorthanded to t), not raising an error on EOF (the EOF return value is optional and defaults to nil). The line is returned as a string without the trialing "\n".

(format t "~4t~A~%" l)

Prints out formatted text to *standard-output* (shorthanded to t). "~4t~A~%" is a formatting string. ~4t moves to the fourth column (prints 4 spaces), ~A prints out an argument to format, ~% prints out a newline.

(loop :for l := ... :while l :do ...)

Each time through the loop, assign l to the result of reading in a line of text, break the loop if there was no line to read, and print out the line with four spaces prepended.

djeis

Posted 2017-04-08T19:24:47.833

Reputation: 281

Many implementations would not require the leading colons for loop keywords, which could save you a few bites. – Julian Wolf – 2017-04-11T17:59:24.027

You know, I'm well aware of that, and yet I keep forgetting it when I do code golf... – djeis – 2017-04-12T16:06:34.527

I think I just really want to forget that that's even a thing. – djeis – 2017-04-12T16:08:48.837

0

C#, 46 35 bytes

s=>"    "+s.Replace("\n","\n    ");

TheLethalCoder

Posted 2017-04-08T19:24:47.833

Reputation: 6 930

0

REXX, 41 bytes

do while lines()>0
say '    'linein()
end

Reads from stdin, writes to stdout.

idrougge

Posted 2017-04-08T19:24:47.833

Reputation: 641

0

Charcoal, 6 bytes

PSM⁴← 

Try it online!

Note: There is a space at the end

Explanation

PS     Print next input as string
   M⁴←  Move 4 cells left
         (it's a space) Print space

ASCII-only

Posted 2017-04-08T19:24:47.833

Reputation: 4 687

Err, including the space, that's 16 bytes in UTF-8. – Papayaman1000 – 2017-04-11T04:46:32.913

Yeah, but Charcoal doesn't use UTF-8 – ASCII-only – 2017-04-11T04:48:34.663

The accepted V answer's first solution is 6 UTF-8 bytes (but 4 V-bytes), so it was counted as such until they introduced a 4-byte UTF-8 solution. – Papayaman1000 – 2017-04-11T04:51:58.400

@Papayaman1000 ... the current V answer isn't in UTF-8 – ASCII-only – 2017-04-11T04:53:43.083

read more of it. – Papayaman1000 – 2017-04-11T04:54:11.873

@Papayaman1000 That's just pretty much a bonus answer, it doesn't have to be in UTF-8 at all – ASCII-only – 2017-04-11T04:54:49.177

ok, fair enough. – Papayaman1000 – 2017-04-11T05:17:47.953

@Papayaman1000 Yeah, a lot of esolangs here use custom codepages e.g. Actually/Jelly/V/Charcoal – ASCII-only – 2017-04-11T05:18:50.473

@Papayaman1000 Yeah, as ASCII-only said, the 4 byte UTF-8 V answer was just a bonus. But the V answer is enocded in Latin1, not UTF-8, where it is 4 bytes despite being 6 bytes in UTF-8. For reference, you can see Charcoal's Code Page here: https://github.com/somebody1234/Charcoal/wiki/Code-page

– user41805 – 2017-04-11T07:37:16.440

0

Carrot, 22 bytes, non-competing

Non-competing because of a bug with the website not showing leading whitespace in the output that was fixed recently

    #^//^.*/gmS"
    "

(note the leading spaces on each of the lines)

Try it online here.

Explanation

First we are in caret mode, where every character gets pushed to the stack (which is just a string). The four leading spaces on the first line push these spaces to the stack. Then the # pushes all of the input to the stack. Now the first line has four leading spaces. And the ^ takes us out of caret mode.

Next comes the / operator. The function of each operator depends on the argument it takes. In this case, the operator takes in a regex as its argument. The / operator with a regex argument returns the matches of the regex. The regex is /^.*/gm, this matches every line in the stack (except for the newlines). Now the stack turns from being a string into an array that contains the matches.

The S operator with a string argument joins the elements of the stack array with the argument. So in this case, we are joining the matches with this string, \n .

To simplify what was done here, the program prepends 4 spaces to the input and then substitutes newlines with a newline and 4 spaces (I really need to add a substitution operator to Carrot).

user41805

Posted 2017-04-08T19:24:47.833

Reputation: 16 320

0

Mathematica, 34 bytes

(Needs version 10.)

StringReplace[StartOfLine->"    "]

Explanation: A string replacement operator where the start of each line is turned into " ".

Not a tree

Posted 2017-04-08T19:24:47.833

Reputation: 3 106

0

Tcl, 40

puts [regsub -all ^ [read stdin] "    "]

demo — Notes:

  • Avoid to press backspace key, it will execute the browser's History back.
  • To end the input press Ctrl+D after you had input all lines (you may have to press two times has it tends to get absorbed has a browser keybinding). If you paste the on a Windows interpreter, use Ctrl+Z+Enter to mark end of input.
  • Pressing arrow keys will make appear strange chars instead of moving cursor.
  • Yes, online interpreters really suck
  • The rest of code is only for input and output, does not really process the string

sergiol

Posted 2017-04-08T19:24:47.833

Reputation: 3 055

Are... are you familiar with bash? Because some of those "issues" sound like any normal CLI. Furthermore, I have no issues with keybinds or anything (maybe your browser just sucks?). Finally, in/out is a necessary part of this program, as per the rules; include it in the snippet and the byte count. – Papayaman1000 – 2017-04-25T18:28:00.433

I didn't touch a real Linux/Unix shell for years but you made me recall where such come from; they are not happening on my local Windows machine. May be the browser (Vivaldi) is absorbing keybindings when it should not. Updated to include output and input part; updated also the link to the new script demo. I think I can reduce the byte count to less if I make a function instead of user I/O. – sergiol – 2017-04-25T21:21:29.597

BTW, the Mathematica answer also seems to not have IO part – sergiol – 2017-04-25T21:24:51.387

0

Tcl, 40

Now as a function:

proc p t {regsub -all -line ^ $t "    "}

demo

Did not save bytes after all!

sergiol

Posted 2017-04-08T19:24:47.833

Reputation: 3 055

0

Cubix, 28 bytes

v.@>i??soS4.^(s<.....u!-Ns<v

Try it online!

Net form:

      v . @
      > i ?
      ? s o
S 4 . ^ ( s < . . . . .
u ! - N s < v . . . . .
. . . . . . . . . . . .
      . . .
      . . .
      . . .

Explanation coming soon...

Luke

Posted 2017-04-08T19:24:47.833

Reputation: 4 675