[Question]
  [
# Center The Text!
In this challenge you will be centering various lines.
## Examples
```
Foo
barbaz
 Foo
barbaz
```
```
Hello
World
Hello
World
```
```
Programming Puzzles
&
Code Golf
Programming Puzzles
         &
     Code Golf
```
## Specifications
Each input line will always have at least one non-whitespace character, you may assume the only whitespace character are spaces () and newlines. Each input line won't have any trailing and/or leading whitespace (except for the newline). Trailing whitespace in the output is *not* allowed.
You should be centering among the longest line in the input. If that line is even in length, your program/function should prefer to center to the left. The maximum line length is whatever your language can handle but your program should function on lines of at least 500 in length.
---
## Leaderboard
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
# Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
# Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
# Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the leaderboard snippet:
```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
var QUESTION_ID=66731,OVERRIDE_USER=8478;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes wins!
  
[Answer]
## vim, ~~43~~ ~~36~~ 35 bytes
```
VGrx:sor
G:let &tw=col("$")
uu:%ce
```
Too good not to post. Note the trailing newline; it is significant.
Thanks to [@Marth](https://codegolf.stackexchange.com/users/30991/marth) for saving a character!
vim-friendly format:
```
VGrx:sor<cr>G:let &tw=col("$")<cr>uu:%ce<cr>
```
Explanation:
```
VGrx                   replace every character with an "x"
:sor<cr>               sort (since all chars are now same, sorts by line length)
G                      go to the very last line
:let &tw=col("$")<cr>  set &tw to column number of last char on this line
                         "let &tw" is equivalent to "set tw"
                         tw is short for textwidth, used in :center
uu                     undo the sort, and the replacing-with-x too
:%ce<cr>               center over entire file (%), using textwidth set earlier
```
[Answer]
## Mathematica, 96 bytes
```
StringRiffle[#~StringPadLeft~Floor[Max@(l=StringLength)@a/2+l@#/2]&/@(a=#~StringSplit~"
"),"
"]&
```
Don't ask me how it worked, I just fiddled with it until it produced the correct output.
[Answer]
# Pyth, ~~19~~ 17 bytes
*2 bytes thanks to Jakube*
```
V.ztr+1.[l.T.zNd6
```
[Demonstration](https://pyth.herokuapp.com/?code=V.ztr%2B1.%5Bl.T.zNd6&input=Foo%0Abarbaz&debug=0)
I think this is the first time the center-pad function of `.[` has been useful. The length of the longest line is found using non-truncating transpose (`.T`).
Trailing spaces are removed by adding a non-space character to the front, stripping spaces, then removing the added character.
[Answer]
# [Funciton](http://esolangs.org/wiki/Funciton), non-competitive
This challenge has highlighted the sore lack of a “maximum value” (and minimum value) function for lazy sequences, so... I added them to the core library (they’re called ⊤ and ⊥, respectively). Therefore I didn’t bother to submit this as a *golfed* answer (it would have to include the ⊤ function declaration to be valid), so here’s just the main program.
Execute `(function(){$('pre,code').css({lineHeight:5/4,fontFamily:'DejaVu Sans Mono'});})()` in your browser console to get some nicer rendering.
```
   ╓───╖         ╔════╗  ┌───╖  ╔═══╗
 ┌─╢ ‡ ╟─┐       ║ 10 ╟──┤ ǁ ╟──╢   ║
 │ ╙───╜ │       ╚════╝  ╘═╤═╝  ╚═══╝
 │ ┌───╖ │  ┌──────────────┴──────────────────┐
 └─┤ ‼ ╟─┘┌─┴─╖ ┌───╖ ┌───╖ ┌───╖ ┌───╖       │     │
   ╘═╤═╝  │ ɱ ╟─┤ ⊤ ╟─┤ + ╟─┤ ~ ╟─┤ ℓ ╟───┐ ┌─┴─╖ ┌─┴─╖ ╔════╗
     │    ╘═╤═╝ ╘═══╝ ╘═╤═╝ ╘═══╝ ╘═══╝   │ │ ɱ ╟─┤ ʝ ╟─╢ 10 ║
    ┌───╖ ╔═╧═╕ ╔═══╗ ┌─┴──╖ ┌───╖ ╔════╗ │ ╘═╤═╝ ╘═══╝ ╚════╝
  ┌─┤ ℓ ╟─╢   ├─╢ 1 ║ │ >> ╟─┤ … ╟─╢ 32 ║ │   │
  │ ╘═══╝ ╚═╤═╛ ╚═╤═╝ ╘═╤══╝ ╘═╤═╝ ╚════╝ │ ╔═╧═╕ ╔═══╗
  └─────────┘     └─────┘      │   ┌───╖  ├─╢   ├─╢ 0 ║
                               └───┤ ‡ ╟──┘ ╚═╤═╛ ╚═══╝
                                   ╘═╤═╝      │
                                     └────────┘
```
## Explanation
I believe this may be the first Funciton answer on this site that uses lambda expressions.
* First, we use `ǁ` to split the input string at the newlines (ASCII 10). This returns a lazy sequence.
* We pass that sequence through `ɱ` (map), giving it a lambda that calculates the length of each string, and then pass the final sequence through `⊤` to get the length of the longest line.
* We *also* pass that sequence through another `ɱ`, giving it a lambda that calculates the length of each string, subtracts it from the maximum line length calculated earlier, divides that by 2 (actually shift-right 1), generates that many spaces (ASCII 32) and then concatenates the string onto those spaces. (For geometric reasons, I declared a `‡` function that calls `‼` (string concatenate) with the parameters reversed.)
* Finally, we use `ʝ` to put all of the strings back together, using newlines (ASCII 10) as the separator.
[Answer]
## [Retina](https://github.com/mbuettner/retina), ~~54~~ 52 bytes
```
+m`^(.)+$(?<=(?=[^\t]*^..(?<-1>.)+(?(1)^))[^\t]*)
 $0 
```
The `\t`s can replaced with actual tabs, but I've used `\t` here, because otherwise SE will convert the tabs to spaces. Note that there is a leading space on the second line.
[Try it online.](http://retina.tryitonline.net/#code=K21gXiguKSskKD88PSg_PVteCV0qXi4uKD88LTE-LikrKD8oMSleKSlbXgldKikKICQwIA&input=UHJvZ3JhbW1pbmcgUHV6emxlcwomCkNvZGUgR29sZg)
### Explanation
The basic idea is to match a line which is at least two characters shorter than the longest line (or technically, two characters shorter than *any* other line), and surround it in two spaces. This is repeated until we can no longer find such a line, which means that all lines are within one character of the maximum length (where the one character is to account for parity mismatches, and guarantees that these lines are shifted to the left off-centre).
As for the actual regex:
```
^(.)+$
```
Just matches any one line while pushing one capture onto group `1` for each character.
```
(?<=...[^\t]*)
```
Is a lookbehind which is matched right-to-left and moves the cursor to the beginning of the string, so that the lookahead inside can check the entire string. Note that due to a lack of an anchor, the lookahead could be applied from anywhere else, but that does not create additional matches. We know that `[^\t]` will always match *any* character in the string, because the input is guaranteed to contain only spaces and linefeeds as far as whitespace is concerned.
```
(?=[^\t]*^..(?<-1>.)+(?(1)^))
```
This lookahead tries to find a line which is at least two characters longer than the one we're currently matching. `[^\t]*` moves through the string in order to be able to match any line. `^` ensures that we're starting from the beginning of the line. `..` then matches the two additional characters we require for the longer line. Now `(?<-1>.)+` matches individual characters in that line while popping from group `1` (note that `.` cannot match a linefeed, so this is constrained to one line). Finally, `(?(1)^)` asserts that we managed to empty the entire group `1`. If the line is shorter than required, this is not possible, because there are not enough characters in the line to pop from group 1 often enough to empty it.
[Answer]
# [Jolf](https://github.com/ConorOBrien-Foxx/Jolf), 3 bytes
*Noncompeting, update postdates question.*
[Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=cGNp&input=UHJvZ3JhbW1pbmcgUHV6emxlcwomCkNvZGUgR29sZg).
```
pci
pc  center
  i  string input
```
¯\\_(ツ)\_/¯ I thought it'd be a useful function.
[Answer]
# JavaScript (ES6), ~~93~~ 91 bytes
```
s=>(m=l=s.split`
`).map(x=>(v=x.length/2)<m?v:m=v).map((x,i)=>" ".repeat(m-x)+l[i]).join`
`
```
*2 bytes saved thanks to [@edc65](https://codegolf.stackexchange.com/users/21348/edc65)!*
## Explanation
```
s=>(
  m=                // m = max line length (divided by 2)
    l=s.split`
`)                  // l = array of lines
.map(x=>            // for each line
  (v=x.length/2)    // v = current line length / 2
    <m?v:m=v        // set m to the max line length and return v
)
.map((x,i)=>        // for each line length / 2
  " ".repeat(m-x)   // add spaces before
    +l[i]           // add line text
)
.join`
`                   // return lines as a newline-separated string
```
## Test
```
var solution = s=>(m=l=s.split`
`).map(x=>(v=x.length/2)<m?v:m=v).map((x,i)=>" ".repeat(m-x)+l[i]).join`
`
```
```
<textarea id="input" rows="4" cols="20">Programming Puzzles
&
Code Golf</textarea><br />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
[Answer]
# CJam, ~~26~~ ~~23~~ 19 bytes
```
qN/_z,f{1$,m2/S*\N}
```
My first time using CJam! Four bytes saved thanks to Martin Büttner. [Try it online.](http://cjam.aditsu.net/#code=qN%2F_z%2Cf%7B1%24%2Cm2%2FS*%5CN%7D&input=Programming%20Puzzles%0A%26%0ACode%20Golf)
### Explanation
```
qN/    e# Read input and split each line
_z,    e# Transpose a copy and get its length to find the longest line
f{     e# For each line...
  1$,- e# Subtract its length from the longest length
  2/   e# Divide by two to get just the spaces to add to the left
  S*\  e# Add a string with that many spaces to the beginning
  N    e# Add a newline to go on to the next line
}
```
[Answer]
# LabVIEW, 3 or 35 [LabVIEW Primitives](http://meta.codegolf.stackexchange.com/a/7589/39490)
Finds lines until none are left, then calculates how many spaces to add and puts everything together.
[![](https://i.stack.imgur.com/9SHUE.gif)](https://i.stack.imgur.com/9SHUE.gif)
Alternatively you could use the built-in center alignment on string indicators, it kinda does feel like cheating though.
[![](https://i.stack.imgur.com/CiOoK.jpg)](https://i.stack.imgur.com/CiOoK.jpg)
[Answer]
# Python 2, ~~83~~ 81 bytes
```
def f(s):
 t=s.split('\n')
 for y in t:print(max(len(f)for f in t)-len(y))/2*' '+y  
```
Thanks to @xnor for saving 2 chars
example input:
```
f("""Programming Puzzles
&
Code Golf""")
```
example output:
```
Programming Puzzles
         &
     Code Golf
```
And ending in second place with 84 bytes using str.center() and str.rstrip (thanks @J F).
```
def f(s):
 t=s.split('\n')
 for y in t:print y.center(max(len(f)for f in t)).rstrip()
```
[Answer]
# [TeaScript](http://github.com/vihanb/TeaScript), 24 bytes
```
£p.R((aßln)¯-ln)/2)+l,§)
```
Loops through lines, adds `floor((max line length - line length) / 2)` spaces to the beginning.
## Ungolfed
```
£   p.R((aß  ln)¯  -ln)/2)+l,§   )
xl(#p.R((am(#ln)X()-ln)/2)+l,`\n`)
xl(#    // Loops through newlines
    p.R(   // Repeats spaces
      (
       am(#ln)    // Map all line lengths
              X() // Get largest line length
       -ln)       // Subtract current line length
      /2)  // Divide by two
      +l,  // Add current line text
`\n`)
```
[Try it online](http://vihanserver.tk/p/TeaScript/#?code=%22%C2%A3p.R((a%C3%9Fln)%C2%AF-ln)%2F2)%2Bl,%C2%A7)%22&inputs=%5B%22Programming%20Puzzles%5Cn%26%5CnCode%20Golf%22%5D&opts=%7B%22int%22:false,%22ar%22:false,%22debug%22:false,%22chars%22:false,%22html%22:false%7D)
[Answer]
# PowerShell, 58 67 bytes
down to 58 bytes thanks to @mazzy's comments:
```
param($a)$a|%{$_|% *ft(($a|% le*|sort)[-1]/2+$_.length/2)}
# It takes an array of strings as input
PS C:\Temp> .\center.ps1 'aaa','bb','c'
aaa
bb
 c
# Or here, read from a file
PS C:\Temp> .\center.ps1 (gc t.txt)
info0:info1:info2:info3
      info0:info1
          ttt
          tt
           t
```
* It takes an array of strings as `$a`, loops over each string with `|%{...}`.
* calls the `string.padleft()` method on each string, via `% -member` shortcut, which takes desired final line length as a parameter.
	+ we need `array_longest_line_length/2 + current_line_length/2`
	+ the end part is `current_line_length/2` -> `$_.length/2`
	+ the other part is recalculating the array's maximum line length every time through the loop, and it does so with a nested loop making an array of line lengths, sorts that, then takes the last one.
[Answer]
# Emacs Lisp, 203 bytes
```
(let((f 0)(l 0))(dolist(s(split-string(buffer-string)"\n"))(set'l(string-width s))(when(> l f)(set'f l)))(let((fill-column f))(goto-char(point-min))(while(<(point)(point-max))(center-line)(next-line)))))
```
Ungolfed:
```
(let ((f 0) (l 0))
  (dolist (s (split-string(buffer-string) "\n"))
    (set 'l (string-width s))
    (when (> l f)
      (set 'f l)))
    (let ((fill-column f))
      (goto-char (point-min))
      (while (< (point) (point-max))
        (center-line)
        (next-line)))))
```
Centered:
```
               (let ((f 0) (l 0))
 (dolist (s (split-string(buffer-string) "\n"))
           (set 'l (string-width s))
                 (when (> l f)
                  (set 'f l)))
             (let ((fill-column f))
            (goto-char (point-min))
         (while (< (point) (point-max))
                 (center-line)
                (next-line)))))
```
[Answer]
# Ruby, ~~76~~ ~~68~~ 61 bytes
```
->t{(s=t.split$/).map{|l|l.center(s.map(&:size).max).rstrip}}
```
Sample run:
```
2.1.5 :001 > puts ->t{(s=t.split$/).map{|l|l.center(s.map(&:size).max).rstrip}}["Programming Puzzles\n&\nCode Golf"]
Programming Puzzles
         &
     Code Golf
```
[Answer]
## HTML, 40 bytes
```
<xmp style=float:left;text-align:center>
```
```
<xmp style=float:left;text-align:center>
Programming Puzzles
&
Code Golf
</xmp>
```
Snippet includes `</xmp>` tag because the code snippet viewer wants my tags to be balanced.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 22 ~~31~~ bytes
```
`jtYz~]xXhc4X4H$ZuZ{Zv
```
Each line is input with a trailing line (that is, an `enter` keystroke). An empty line (two `enter` keystrokes) marks the end of input.
### Example
```
>> matl `jtYz~]xXhc4X4H$ZuZ{Zv
> foo
> barbaz
> 
 foo
barbaz
```
### Explanation
```
`          % do...
  j        % input one string
  tYz~     % is it not empty?
]          % ...while
x          % delete last input (empty string)
Xh         % concatenate all inputs into a cell array
c          % convert to char (2D array). This fills with spaces to the right
4X4H$Zu    % center justify
Z{         % convert to cell array of strings
Zv         % remove trailing blanks of each string
```
[Answer]
# Haskell, ~~111~~ ~~81~~ 77 bytes
```
l=length
f s|q<-lines s=unlines[([1..div(maximum(l<$>q)-l w)2]>>" ")++w|w<-q]
```
Input to the f function, the output is not printed.
Usage: load in interpreter `ghci center.hs` and then if you want to print the output of f on a given string `putStr$f"Programming Puzzles\n&\nCode Golf"`
Edit: Thanks to [nimi](https://codegolf.stackexchange.com/users/34531/nimi) for 34 bytes, great job! :D
[Answer]
# R, 126 bytes
### code
```
for(z in 1){l=scan(,"");m=sapply(l,nchar);t=max(m[m==max(m)]);for(i in 1:length(m))cat(rep(" ",(t-m[i])/2),l[i],"\n", sep="")}
```
### ungolfed
```
for(z in 1){                          # any way to get rid of this?
  l=scan(,"")
  m <- sapply(l,nchar)
  t <- max(m[m==max(m)])
  for(i in 1:length(m)){
    cat(rep(" ",(t-m[i])/2),l[i],"\n", sep="")
  }
}
```
Probably there are waay better ways to do this, still working on it.
[Answer]
# Gema, 160 bytes
```
\L<T>=@push{i;$0}@set{m;@cmpn{@length{$0};${m;};$m;$m;@length{$0}}}
?=
\Z=@repeat{@sub{@line;1};@set{o;@right{@div{@add{$m;@length{$i}};2};$i}\n${o;}}@pop{i}}$o
```
Written mostly for my curiosity to see what can be done in a language without proper array structure and proper loop instruction.
Sample run:
```
bash-4.3$ gema '\L<T>=@push{i;$0}@set{m;@cmpn{@length{$0};${m;};$m;$m;@length{$0}}};?=;\Z=@repeat{@sub{@line;1};@set{o;@right{@div{@add{$m;@length{$i}};2};$i}\n${o;}}@pop{i}}$o' <<< $'Programming Puzzles\n&\nCode Golf'
Programming Puzzles
         &
     Code Golf
```
[Answer]
# [Perl 6](http://perl6.org), 61 bytes
```
$/=(my@l=lines)».chars.max;for @l {put ' 'x($/-.chars)/2~$_} # 61 bytes
```
usage:
```
$ perl6 -e '$/=(my@l=lines)».chars.max;for @l {put " "x($/-.chars)/2~$_}' <<< \
'Programming Puzzles
&
Code Golf'
```
```
Programming Puzzles
         &
     Code Golf
```
[Answer]
# Japt, ~~28~~ 25
```
¡V=VwXl}R;¡Sp½*(V-Xl¹+X}R
```
[Try it online!](http://ethproductions.github.io/japt?v=master&code=oVY9VndYbH1SO6FTcL0qKFYtWGy5K1h9Ug==&input=IlByb2dyYW1taW5nIFB1enpsZXMKJgpDb2RlIEdvbGYi)
### How it works
```
¡     V=VwXl}R;¡     Sp½*(V-Xl¹ +X}R
UmXYZ{V=VwXl}R;UmXYZ{Sp½*(V-Xl) +X}R
           // Implicit: U = input string, V = 0
UmXYZ{  }  // Map each item X in U through this function,
         R // splitting U at newlines beforehand:
  V=VwXl   //  Set V to max(X, Y.length).
           // V is now set to the length of the longest line.
UmXYZ{  }  // Map each item X in U with this function,
         R // again splitting U at newlines beforehand:
 ½*(V-Xl)  //  Take V minus X.length, and multiply by 1/2.
Sp         //  Repeat a space that many times.
        +X //  Concatenate X to the end.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 2 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.c
```
Builtins ftw ¯\\_(ツ)\_/¯
[Try it online](https://tio.run/##yy9OTMpM/f9fL/n/fyUlpYCi/PSixNzczLx0hYDSqqqc1GIuNS7n/JRUBff8nDSgCgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9W@V8v@b/OoW32/6OV3PLzY/KSEouSEquUdJQ8UnNygPzw/KKcFCA3oCg/vSgxNzczL10hoLSqKie1OCZPLSbPOT8lVcE9PydNKRYA).
**Explanation:**
```
.c   # Centralize the (implicit) multi-line input-string with preference to the left
     # (output the result implicitly)
```
(Preference to the right would be with a capital `.C` instead: [see the differences](https://tio.run/##yy9OTMpM/f9fySc1rUShoCg1LbUoNS851UpJx1MvWefQNnuloMz0DAwpZx2gHiUlt/x8rqTEoqTEKiAHAA).)
[Answer]
# [PHP](https://php.net/), 98 bytes
```
function($s){foreach($a=explode("
",$s)as$l)echo str_pad($l,max(array_map(strlen,$a)),' ',2),"
";}
```
[Try it online!](https://tio.run/##Dc5NCsIwEEDhfU8RJNgJBBSX1uLChVtvEIZ20hbSTJhE8AfPXrN@PPjSnLbLNc1JkQiLE0osZYkTHE2ntO83/4xDWTiCzubrWQiHGTT29EqBR4Jds7M1YdbB0DCzykVcwhF0sCu@AEXw7VZMUEOgaDUaY1vV2pOxde5@W6c9@CWQm6i4gWOhWDK0VXU@HHIZl9ga020P4UlwXatOPZ6fT6Dc7JtbRag7B/8H "PHP – Try It Online")
Ungolfed:
```
function str_center( $s ) {
    $a = explode( PHP_EOL, $s );
    $m = max( array_map( 'strlen', $a ) );
    foreach( $a as $l ) {
        echo str_pad( $l, $m, ' ', STR_PAD_BOTH ), PHP_EOL;
    }
}
```
Output:
```
Programming Puzzles
         &         
     Code Golf   
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 1 byte
```
û
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=%2bw==&input=IkZvbwpiYXJiYXoi) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW1S&code=%2bw==&input=WyJGb28KYmFyYmF6IgoiSGVsbG8KV29ybGQiCiJQcm9ncmFtbWluZyBQdXp6bGVzCiYKQ29kZSBHb2xmIgpd)
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 25 bytes
```
{↑(-⌊((⌈/≢¨⍵)+≢¨⍵)÷2)↑¨⍵}
```
There's an APLcart snippet for centering in a field:
`Is(⊢↑⍨∘-∘⌊2÷⍨+∘≢)Dv`
This answer is partly based on it.
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v/pR20QN3Uc9XRoaj3o69B91Ljq04lHvVk1tOOvwdiNNoCIwp/Z/2qO2CY96@x51NT/qXfOod8uh9cZAyUd9U4ODnIFkiIdn8P80BXW3/Hx1BfWkxKKkxCp1LqAEUJu6OhdQxiM1JwckF55flJOCKhVQlJ9elJibm5mXrhBQWlWVk1oMVKgGxM75KakK7vk5aeoA "APL (Dyalog Extended) – Try It Online")
## Explanation
```
{↑(-⌊((⌈/≢¨⍵)+≢¨⍵)÷2)↑¨⍵}
      (⌈/≢¨⍵)             Maximum of lengths of each line
             +≢¨⍵         Plus length of each line
     (           )÷2      divided by two
   -⌊(           )        Floor it, and take negative
  (                 )↑¨⍵  Take that much from each line
                          (taking a negative value prepends spaces)
 ↑                        Mix the final array to print on each line
{                       } dfn
```
[Answer]
## Pascal, 404 bytes
This complete `program` is suitable for any processor complying with ISO standards 7185 (“Standard Pascal”) or 10206 (“Extended Pascal”).
The `maximumLineLength` algorithm requires that every line has a maximum length of `maxInt` characters.
```
program p(input,output);type Z=integer;var b:text;l:file of Z;c,m:Z;begin
m:=0;c:=0;rewrite(b);rewrite(l);while not EOF do begin if EOLn then begin
write(l,c);c:=0;writeLn(b)end else begin c:=c+1;if c>m then
m:=c;write(b,input^)end;get(input)end;reset(b);reset(l);while not EOF(b)do
begin read(l,c);for c:=1 to(m-c)div 2 do write(' ');while not EOLn(b)do
begin write(b^);get(b)end;writeLn;get(b)end end.
```
Ungolfed:
```
program centerTheText(input, output);
    type
        integerNonNegative = 0‥maxInt;
    
    var
        { The behavior of `reset(input)` is implementation-defined.
          Using a buffer `text` file avoids relying on specific behavior. }
        buffer: text;
        { Stores the length of a line in `input` (buffered in `buffer`). }
        lineLength: file of integerNonNegative;
        { The length of the currently processed line. }
        currentLineLength: integerNonNegative;
        { The length of the longest line found. }
        maximumLineLength: integerNonNegative;
    
    begin
        maximumLineLength ≔ 0;
        currentLineLength ≔ 0;
        { Open files for writing and set their lengths to zero (“truncate”). }
        rewrite(buffer);
        rewrite(lineLength);
        
        { process and analyze `input` ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄ }
        while not EOF(input) do
        begin
            { Invocation of `EOLn(input)` is only valid if `not EOF(input)`. }
            if EOLn(input) then
            begin
                { `input↑` contains a space so we cannot just copy it. }
                writeLn(buffer);
                { Store the determined line length for the centering. }
                write(lineLength, currentLineLength);
                { Prepare `currentLineLength` for the next line. }
                currentLineLength ≔ 0;
            end
            else
            begin
                currentLineLength ≔ currentLineLength + 1;
                { In Extended Pascal you could write: `maximumLineLength ≔
                  card([0‥currentLineLength, 0‥maximumLineLength]) − 1`. }
                if currentLineLength > maximumLineLength then
                begin
                    maximumLineLength ≔ currentLineLength;
                end;
                { For later reference store `input↑` in `buffer`. }
                write(buffer, input↑);
            end;
            { Advance reading cursor. }
            get(input);
        end;
        
        { Open files for reading from the start. }
        reset(buffer);
        reset(lineLength);
        
        { Reproduce `input` but centered. ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄ }
        while not EOF(buffer) do
        begin
            read(lineLength, currentLineLength);
            { In Extended Pascal you could also just write:
              `write('':(maximumLineLength − currentLineLength) div 2)` }
            for currentLineLength ≔ 1 to
                (maximumLineLength − currentLineLength) div 2 do
            begin
                write(output, ' ');
            end;
            { Do not enter loop in case of an empty line. }
            while not EOLn(buffer) do
            begin
                write(output, buffer↑);
                get(buffer);
            end;
            { Discard the end-of-line marker character. }
            get(buffer);
            { Emit the implementation-specific end-of-line marker character. }
            writeLn(output);
        end;
    end.
```
## Extended Pascal, 252 bytes
Requiring a processor compliant with ISO standard 10206 “Extended Pascal” the schema data type `string` becomes available.
Lots of operations can be thus abbreviated:
```
program p(input,output);var b:text;l:string(maxInt);m:integer;begin
m:=0;rewrite(b);while not EOF do begin readLn(l);if m<length(l)then
m:=length(l);writeLn(b,l)end;reset(b);while not EOF(b)do begin
readLn(b,l);writeLn('':(m-length(l))div 2,l)end end.
```
Ungolfed:
```
program centerTheText(input, output);
    type
        { `integer…` prefix to facilitate sorting in documentation tools. }
        integerNonNegative = 0‥maxInt;
    
    var
        buffer: text;
        line: string(maxInt);
        maximumLineLength: integerNonNegative value 0;
    
    begin
        { The size of `buffer` immediately becomes zero. }
        rewrite(buffer);
        { Find the length of the longest line in `input`. }
        while not EOF(input) do
        begin
            readLn(input, line);
            { Is the current line longer than the longest line so far? }
            if length(line) > maximumLineLength then
            begin
                maximumLineLength ≔ length(line);
            end;
            { Store the read `input` line in `buffer` for later retrieval. }
            writeLn(buffer, line);
        end;
        
        { (Re‑)open `buffer` and start reading `buffer` from the start. }
        reset(buffer);
        { The `while` loop is not entered in case `buffer` is an empty file. }
        while not EOF(buffer) do
        begin
            readLn(buffer, line);
            { Empty strings (`''`) are only allowed in Extended Pascal.
              For `string` values the `integer` expression after the colon
              dictates the _exact_ width of the string padded with spaces. }
            writeLn('':(maximumLineLength − length(line)) div 2, line);
        end;
    end.
```
]