# Create a codeblock tool

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!

• "you need to indent each line manually" (or select the text and click the button :)) – Jonathan Allan Apr 8 '17 at 19:29
• @JonathanAllan "Button"? Surely you mean "keyboard shortcut". (Ctrl+K) – Martin Ender Apr 8 '17 at 19:29
• @JonathanAllan ...I... I am very upset. SO MUCH TIME. WASTED. – Papayaman1000 Apr 8 '17 at 19:31
• While 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 Apr 8 '17 at 20:12
• +1 for informing people about Ctrl + K – Koishore Roy Apr 9 '17 at 9:54

# 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)

• Hope somebody picks up that phone, cause wow did someone call it. – Papayaman1000 Apr 8 '17 at 19:45
• Alternate solution: 4ñ>G – James Apr 8 '17 at 20:07
• @DJMcMayhem But it uses tabs to indent instead of spaces – user41805 Apr 8 '17 at 20:09
• In vim, yes. In V, no, it's 4 spaces – James Apr 8 '17 at 20:10
• @DJMcMayhem Thanks, that inspired another alternative solution that is only 4 bytes in UTF-8! – user41805 Apr 8 '17 at 20:17

# 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.

• 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. – user62131 Apr 9 '17 at 13:26
• @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 Apr 9 '17 at 18:50

## 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.

• I suspected a Retina answer would be first. – Neil Apr 8 '17 at 19:31
• Well that was fast. – Papayaman1000 Apr 8 '17 at 19:32
• @Neil I'll be surprised if this doesn't get beaten by V (or even raw Vim). :) – Martin Ender Apr 8 '17 at 19:32
• @MartinEnder Here ya go (4 bytes in V): codegolf.stackexchange.com/a/115870/41805 :) – user41805 Apr 8 '17 at 19:44

# 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

• Oh did you change how the parser works? From what I remember : would cause problems with ?: – Conor O'Brien Apr 8 '17 at 20:17
• @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 Apr 8 '17 at 20:20
• +1 for smiley :+) – LarsW Apr 8 '17 at 23:17
• What does @ mean? – Leaky Nun Apr 27 '17 at 10:10

# 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!

• lambda s:' '*4+s.replace('\n','\n ') for 39 bytes – ovs Apr 8 '17 at 20:12
• @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 Apr 8 '17 at 20:16
• Just lambda s:' '*4+s.replace('\n','\n<4 spaces>') TIO – ovs Apr 8 '17 at 20:28
• @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 Apr 8 '17 at 20:30

# 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!

• It seems to jumble non-whitespace in the input into asdf repeated over and over. – Papayaman1000 Apr 8 '17 at 20:16
• You should note what I had put as the input in TIO – fəˈnɛtɪk Apr 8 '17 at 20:17
"|%{" "*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. • Can you use a newline character instead of n? – fergusq Apr 8 '17 at 20:02 • @fergusq indeed I can, updated. – colsw Apr 8 '17 at 20:27 • 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 Apr 10 '17 at 1:58 • @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 Apr 10 '17 at 8:42 # 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  • Got it down to 9: jbm*4\ .z – clap May 9 '17 at 0:43 • @ConfusedMr_C That just overwrites every line with 4 spaces. – KarlKastor May 9 '17 at 19:11 • I forgot the d, whoops. Your 10 byte answer is what I was going for, anyway – clap May 14 '17 at 20:59 # 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 */
}

• Does identity() just pull all values from STDIN? – user41805 Apr 8 '17 at 19:57
• @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 Apr 8 '17 at 20:01

# 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.

• This reads input a line at a time, rather than a string as a whole. – user62131 Apr 9 '17 at 2:21
• @ais523 Roughly half of the answers, including the top two, read input in the exact same way. – Maxim Mikhaylov Apr 9 '17 at 3:39
• @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 Apr 9 '17 at 8:21
• @ais523 after thinking a bit more about it, I think you're right. (I've update my code accordingly) – Dada Apr 9 '17 at 8:40

# 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
)


# sed, 1610 9 bytes

s/^/    /


Try it online!

Edits

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

-1 byte thanks to seshoumara.

• You can get to 15 bytes by using the -r flag (1 byte) so that you can remove the backslashes before the parentheses. – user41805 Apr 9 '17 at 7:52
• You can get to 13 by using s/.*/ &/ (remove the parentheses and replace \1 with &) – user41805 Apr 9 '17 at 7:54
• @KritixiLithos Thanks! It works even without *. – Maxim Mikhaylov Apr 9 '17 at 12:23
• Or simply s:^: :, for 9 bytes. – seshoumara Apr 9 '17 at 17:53
• @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 Apr 9 '17 at 18:37

# 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
• I am forever sad that Java's regex mechanisms require other libraries for the most part. – Poke Apr 10 '17 at 17:30
• I think you need replaceAll – Khaled.K May 9 '17 at 9:36
• @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 May 9 '17 at 11:31

# 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


# PHP, 43 Bytes

<?="    ".strtr($_GET[0],["\n"=>"\n "]);  # 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  # Octave, 17 bytes @(s)[" "';s']'  Try it online! # 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  # 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.

# 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

• 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 Apr 11 '17 at 1:10

# 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.

• 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 Apr 10 '17 at 17:14
• Alright thanks, I removed ZZ then. – daniero Apr 11 '17 at 17:53

# 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

• 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 Apr 15 '17 at 14:49

# 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
(Jumping to d jumps here)
=Ao                                 Read a character to position a.
was nonzero.
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
=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.)


# 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

• Doesn'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 May 9 '17 at 1:40
• @Challenger5 Thanks, corrected! – Luis Mendo May 9 '17 at 7:39

# 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)}


# 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


# C, 66 65 bytes

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


Try it online!

• 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 May 9 '17 at 9:48
• @Khaled.K Thanks, but that doesn't seem to work without including <stdio.h> (because of the stdin). – Steadybox May 9 '17 at 10:06