text:
Unfolding the Hexagony source code
Introduction
If you're not familiar with Hexagony, it's an esoteric language created by Martin Büttner. The thing is that this language accepts multiple forms for the program. The following programs are all equivalent:
abcdefg

and
 a b
c d e
 f g

So basically, the code has been rolled up into a regular hexagon. But note that adding a new command to the code, which would be abcdefgh would result into the following program:
  a b c
 d e f g
h . . . .
 . . . .
  . . .

As you can see, the first step is rolling up the code into a hexagon, and after that the hexagon is filled in with no-ops (.) to the next centered hexagonal number.
Your task is simple, when given a string (the source code), output the full hexagon source code.
The rules

You may provide a program or a function.
Leading whitespace is allowed, but only when the hexagon doesn't get out of shape
Trailing whitespace is allowed.
Note that whitespace in the program are ignored. So a b c is equal to abc
Only the printable ASCII characters (32 - 126) are used, so only the regular Space character is ignored.
Assume that the length of the string is greater than 0.
This is code-golf, so the submission with the least amount of bytes wins!

Test cases
Input: ?({{&2'2':{):!/)'*/

Output:
  ? ( {
 { & 2 '
2 ' : { )
 : ! / )
  ' * /

Input: H;e;l;d;*;r;o;Wl;;o;*433;@.>;23<\4;*/

Output:
   H ; e ;
  l ; d ; *
 ; r ; o ; W
l ; ; o ; * 4
 3 3 ; @ . >
  ; 2 3 < \
   4 ; * /

Input: .?'.) .@@/'/ .!.>   +=(<.!)}    (  $>( <%

Output:
   . ? ' .
  ) . @ @ /
 ' / . ! . >
+ = ( < . ! )
 } ( $ > ( <
  % . . . .
   . . . .

Also, I'm not sure whether you want to be that picky, but backticks are ignored in the process of determining the code width because they annotate the next character. So abc\defg` would actually become http://pastebin.com/ZrdJmHiR

@MartinBüttner Oh, I didn't know that :). For this challenge, backticks will not be ignored.

I really want to see an answer in Hexagony for this question.

@Adnan Probably a better response would be "You can assume that the input contains no debug flags (``` characters)."

@Ampora Ask and you shall receive.

@MartinBüttner Nice work! I was about 24 hours away from offering a bounty to someone who posted a Hexagony answer too.

@Ampora I guess I should have waited 24 hours then. ;)

@MartinBüttner I apologize, I know that for you, reputation is really hard to come by. :P

Pyth, 57 54 50 49 48 46
V+UJfgh*6sUTlK-zd1_UtJ+*d-JNjd:.[K\.^TJZ=+Z+JN

Test Suite
Prints a leading space on each line.
This version requires a proof that 10^n >= 3n(n - 1) + 1 for all n >= 1. Thanks to ANerdI and ErickWong for providing proofs.
Following these inequalities: 10^n > (1+3)^n = 1 + 3n + 9n(n - 1) + ... > 3n(n - 1) + 1 one can easily see that this is correct for n >= 2. Examining the n = 1 case is rather trivial, giving 10 > 1.
Alternatively, taking the derivatives of these equations twice shows that 10^n has a greater second derivative for all n >= 1, which can then be cascaded down to the first derivatives, and finally to the original equations.
Explanation
              ##  Implicit: z=input(); Z=0
Jf...1        ##  Save to J the side length of the hexagon the code fills up
              ##  by finding the first number such that:
gh*6sUT       ##  the the T'th hexagonal number is greater than...
              ##  Computes 6 * T'th triangular number (by using sum 1..T-1) + 1
    lK-zd     ##  ...the length of the code without spaces (also save the string value to K)
V+UJ_UtJ      ##  For loop over N = [0, 1, ..., J-1, ..., 0]:
+*d-JN        ##  append J - N spaces to the front of the line
jd            ##  riffle the result of the next operation with spaces
:.[K\.yJ      ##  slice the string given by K padded to be the length of the Jth hexagon
              ##  number with noops
Z=+Z+JN       ##  from Z to Z + J + N, then set Z to be Z + J + N

First you need to prove that ln(10)10^n>6n-3 (the derivatives) for n>=1. This is easy, as the derivatives of these expressions are ln(10)^2 10^n and 6. Since 10^n is monotonically increasing and 10^1>61, 10^n is greater than 6n-3 for all n>=1. You can use the same logic to complete the proof for 10^n and 3n(n-1)+1.

@Ampora Thanks, I had considered using derivatives, but it seemed unclean. I couldn't find a better way though, so much appreciated!

Glad to help. Calc can get realllly ugly sometimes.

in the link https://pyth.herokuapp.com/?code=etc above i find the compiler not run...

@RosLuP I'm sorry, but I can't reproduce your problem. Are you sure you didn't change anything from what the permalink gives? If you did change something, could you let me know what it is?

@FryAmTheEggman There's a very easy way to show the much stronger bound 4^n > 3n(n-1) + 1 for n>=1, no calculus required.  Just use the fact that (1 + 3)^n = 1 + 3n + 9n(n-1)/2 + ... by binomial expansion.  The first and third terms directly majorize 1 + 3n(n-1), so the inequality is immediate if the third term exists (that is, for n>=2).  This leaves only the case n=1 which is trivial since the RHS is 1.

@ErickWong Thanks! That was more the kind of solution I was looking for, I guess I should have asked on math.se :P I'll edit that proof in as well.

Hexagony, 271 bytes
I present to you, the first 3% of a Hexagony self-interpreter...
|./...\..._..>}{<$}=<;>'<..../;<_'\{*46\..8._~;/;{{;<..|M..'{.>{{=.<.).|.."~....._.>(=</.\=\'$/}{<}.\../>../..._>../_....@/{$|....>...</..~\.>,<$/'";{}({/>-'(<\=&\><${~-"~<$)<....'.>=&'*){=&')&}\'\'2"'23}}_}&<_3.>.'*)'-<>{=/{\*={(&)'){\$<....={\>}}}\&32'-<=._.)}=)+'_+'&<

Try it online! You can also run it on itself, but it will take about 5-10 seconds.
In principle this might fit into side-length 9 (for a score of 217 or less), because this uses only 201 commands, and the ungolfed version I wrote first (on side-length 30) needed only 178 commands. However, I'm pretty sure it would take forever to actually make everything fit, so I'm not sure whether I'll actually attempt it.
It should also be possible to golf this a bit in size 10 by avoiding the use of the last one or two rows, such that the trailing no-ops can be omitted, but that would require a substantial rewrite, as one of the first path joins makes use of the bottom left corner.
Explanation
Let's start by unfolding the code and annotating the control flow paths:

That's still quite messy, so here is the same diagram for the "ungolfed" code which I wrote first (in fact, this is side-length 20 and originally I wrote the code on side-length 30 but that was so sparse that it wouldn't improve the readability at all, so I compacted it just a little bit to make the size a bit more reasonable):

Click for larger version.
The colours are exactly the same apart from a few very minor details, the non-control-flow commands are also exactly the same. So I'll be explaining how this works based on the ungolfed version, and if you really want to know how the golfed one works, you can check which parts there correspond to which in the larger hexagon. (The only catch is that the golfed code starts with a mirror so that the actual code begins in the right corner going left.)
The basic algorithm is almost identical to my CJam answer. There are two differences:

Instead of solving the centred hexagonal number equation, I just compute consecutive centred hexagonal numbers until one is equal to or larger than the length of the input. This is because Hexagony does not have a simple way to compute a square root.
Instead of padding the input with no-ops right away, I check later if I've already exhausted the commands in the input and print a . instead if I have.

That means the basic idea boils down to:

Read and store input string while computing its length.
Find the smallest side-length N (and corresponding centred hexagonal number hex(N)) which can hold the entire input.
Compute the diameter 2N-1.
For each line, compute the indent and the number of cells (which sum to 2N-1). Print the indent, print the cells (using . if the input is already exhausted), print a linefeed.

Note that there are only no-ops so the actual code starts in the left corner (the $, which jumps over the >, so the we really start on the , in the dark grey path).
Here is the initial memory grid:

So the memory pointer starts out on edge labelled input, pointing North. , reads a byte from STDIN or a -1 if we've hit EOF into that edge. Hence, the < right after is a conditional for whether we've read all the input. Let's remain in the input loop for now. The next code we execute is
{&32'-

This writes a 32 into the edge labelled space, and then subtracts it from the input value in the edge labelled diff. Note that this can never be negative because we're guaranteed that the input contains only printable ASCII. It will be zero when the input was a space. (As Timwi points out, this would still work if the input could contain linefeeds or tabs, but it would also strip out all other unprintable characters with character codes less than 32.) In that case, the < deflects the instruction pointer (IP) left and the light grey path is taken. That path simply resets the position of the MP with {= and then reads the next character - thus, spaces are skipped. Otherwise, if the character was not a space, we execute
=}}})&'+'+)=}

This first moves around the hexagon through the length edge until its opposite the diff edge, with =}}}. Then it copies the value from opposite the length edge into the length edge, and increments it with )&'+'+). We'll see in a second why this makes sense. Finally, we move the a new edge with =}:

(The particular edge values are from the last test case given in the challenge.) At this point, the loop repeats, but with everything shifted one hexagon northeast. So after reading another character, we get this:

Now you can see that we're gradually writing the input (minus spaces) along the northeast diagonal, with the characters on every other edge, and the length up to that character being stored parallel to the edge labelled length.
When we're done with the input loop, memory will look like this (where I've already labelled a few new edges for the next part):

The % is the last character we read, the 29 is the number of non-space characters we read. Now we want to find the side-length of the hexagon. First, there is some linear initialisation code in the dark green/grey path:
=&''3{

Here, =& copies the length (29 in our example) into the edge labelled length. Then ''3 moves to the edge labelled 3 and sets its value to 3 (which we just need as a constant in the computation). Finally { moves to the edge labelled N(N-1).
Now we enter the blue loop. This loop increments N (stored in the cell labelled N) then computes its centered hexagonal number and subtracts it from the input length. The linear code which does that is:
{)')&({=*'*)'-

Here, {) moves to and increments N. ')&( moves to edge labelled N-1, copies N there and decrements it. {=* computes their product in N(N-1). '*) multiplies that by the constant 3 and increments the result in the edge labelled hex(N). As expected, this is the Nth centered hexagonal number. Finally '- computes the difference between that and the input length. If the result is positive, the side-length is not large enough yet, and the loop repeats (where }} move the MP back to the edge labelled N(N-1)).
Once the side-length is large enough, the difference will be zero or negative and we get this:

First off, there is now the really long linear green path which does some necessary initialisation for the output loop:
{=&}}}32'"2'=&'*){=&')&}}

The {=& starts by copying the result in the diff edge into the length edge, because we later need something non-positive there. }}}32 writes a 32 into the edge labelled space. '"2 writes a constant 2 into the unlabelled edge above diff. '=& copies N-1 into the second edge with the same label. '*) multiplies it by 2 and increments it so that we get the correct value in the edge labelled 2N-1 at the top. This is the diameter of the hexagon. {=&')& copies the diameter into the other edge labelled 2N-1. Finally }} moves back to the edge labelled 2N-1 at the top.
Let's relabel the edges:

The edge we're currently on (which still holds the diameter of the hexagon) will be used to iterate over the lines of the output. The edge labelled indent will compute how many spaces are needed on the current line. The edge labelled cells will be used to iterate over the number of cells in the current line.
We're now on the pink path which computes indent. ('- decrements the lines iterator and subtracts it from N-1 (into the indent edge). The short blue/grey branch in the code simply computes the modulus of the result (~ negates the value if it's negative or zero, and nothing happens if it's positive). The rest of the pink path is "-~{ which subtracts the indent from the diameter into the cells edge and then moves back to the indent edge.
The dirty yellow path now prints the indentation. The loop contents are really just
'";{}(

Where '" moves to the space edge, ; prints it, {} moves back to indent and ( decrements it.
When we're done with that the (second) dark grey path searches for next character to print. The =} moves in position (which means, onto the cells edge, pointing South). Then we have a very tight loop of {} which simply moves down two edges in the South-West direction, until we hit the end of the stored string:

Notice that I've relabelled one edge there EOF?. Once we've processed this character, we'll make that edge negative, so that the {} loop will terminate here instead of the next iteration:

In the code, we're at the end of the dark grey path, where ' moves back one step onto the input character. If the situation is one of the last two diagrams (i.e. there's still a character from the input we haven't printed yet), then we're taking the green path (the bottom one, for people who aren't good with green and blue). That one is fairly simple: ; prints the character itself. ' moves to the corresponding space edge which still holds a 32 from earlier and ; prints that space. Then {~ makes our EOF? negative for the next iteration, ' moves a back a step so that we can return to the North-West end of the string with another tight }{ loop. Which ends on the length cell (the non-positive one below hex(N). Finally } moves back to the cells edge.
If we've already exhausted the input though, then the loop which searches for EOF? will actually terminate here:

In that case ' moves onto the length cell, and we're taking the light blue (top) path instead, which prints a no-op. The code in this branch is linear:
{*46;{{;{{=

The {*46; writes a 46 into the edge labelled no-op and prints it (i.e. a period). Then {{; moves to the space edge and prints that. The {{= moves back to the cells edge for the next iteration.
At this point the paths join back together and ( decrements the cells edge. If the iterator is not zero yet, we will take the light grey path, which simply reverses the MP's direction with = and then goes looking for the next character to print.
Otherwise, we've reached the end of the current line, and the IP will take the purple path instead. This is what the memory grid looks like at that point:

The purple path contains this:
=M8;~'"=

The = reverses the direction of the MP again. M8 sets the sets its value to 778 (because the character code of M is 77 and digits will append themselves to the current value). This happens to be 10 (mod 256), so when we print it with ;, we get a linefeed. Then ~ makes the edge negative again, '" moves back to the lines edge and = reverses the MP once more.
Now if the lines edge is zero, we're done. The IP will take the (very short) red path, where @ terminates the program. Otherwise, we continue on the purple path which loops back into the pink one, to print another line.

Control flow diagrams created with Timwi's HexagonyColorer. Memory diagrams created with the visual debugger in his Esoteric IDE.

I find myself saying this a lot on hexagony answers: Just whoa.

Huh... but.. wat... mind = blown

I hoped someone would do this and... Wow. I'm speechless. That's awesome.

Step two - write the other 97%. :)

Step three - as the answer with the least bytes.

CJam, 56 52 50 48 bytes
My first thought was, "hey I already have code for this!" But then I couldn't be bothered to pull the necessary pieces together from the Ruby code, especially because they didn't seem very suitable to being golfed. So I tried something else in CJam instead...
lS-{_,4*(3/mq:D1%}{'.+}wD{D(2/-z_S*D@-@/(S*N@s}/

Test it here.
Explanation
A bit of maths about centred hexagonal numbers first. If the regular hexagon has side length N, then it will contain 3N(N-1)+1 cells, which has to equal the source code length k. We can solve that N because it's a simple quadratic equation:
N = 1/2 ± √(1/4 + (k-1)/3)

We can ignore the negative root, because that gives a negative N. For this to have a solution, we need the square root be a half-integer. Or in other words, √(1 + 4(k-1)/3) = √((4k-1)/3) needs to be an integer (luckily, this integer happens to be the diameter D = 2N-1 of the hexagon, which we'll need anyway). So we can repeatedly add a single . until that condition is met.
The rest is a simple loop which lays out the hexagon. A useful observation for this part is that the spaces in the indentation plus the non-spaces in the code in each line add up to the diameter.
lS-     e# Read input and remove spaces.
{       e# While the first block yields something truthy, evaluate the second...
  _,    e#   Duplicate the code and get its length k.
  4*(   e#   Compute 4k-1.
  3/    e#   Divide by 3.
  mq    e#   Take the square root.
  :D    e#   Store this in D, just in case we're done, because when we are, this happens
        e#   to be the diameter of the hexagon.
  1%    e#   Take modulo 1. This is 0 for integers, and non-zero for non-integers.
}{      e# ...
  '.+   e#   Append a no-op to the source code.
}w
D{      e# For every i from 0 to D-1...
  D(2/  e#   Compute (D-1)/2 = N, the side length.
  -z    e#   Subtract that from the current i and get its modulus. That's the size of the
        e#   indentation on this line.
  _S*   e#   Duplicate and get a string with that many spaces.
  D@-   e#   Subtract the other copy from D to get the number of characters of code
        e#   in the current line.
  @/    e#   Pull up the source code and split into chunks of this size.
  (S*   e#   Pull off the first chunk and riffle it with spaces.
  N     e#   Push a linefeed character.
  @s    e#   Pull up the remaining chunks and join them back into a single string.
}/

It turns out that we don't need to use double arithmetic at all (except for the square root). Due to the multiplication by 4, there are no collisions when dividing by 3, and the desired k will be the first to yield an integer square root.

Perl, 203 200 198
includes + 1 for -p
s/\s//g;{($l=y///c)>($h=1+3*++$n*($n-1))&&redo}$s=$_.'.'x($h-$l);for($a=$n;$a<($d=2*$n-1);$a++){$s=~s/.{$a}/$&\n/,$s=reverse($s)for 0..1}$_=join$/,map{(' 'x abs($n-$i++-1)).$_}$s=~/\S+/g;s/\S/ $&/g

run as: echo abc | perl -p file.pl
A very naive approach:
#!/usr/bin/perl -p

s/\s//g;                            # ignore spaces and EOL etc.
{                                   # find the smallest hex number:
    ($l=y///c)                      # calc string length
    > ($h=1+3*++$n*($n-1))          #
    && redo                         # (should use 'and', but..)
}

$s = $_                             # save $_ as it is used in the nested for
   . '.' x ($h-$l);                 # append dots to fill hexagon

for ( $a = $n; $a < ($d=2*$n-1); $a++ )
{
        $s=~s/.{$a}/$&\n/,          # split lines
        $s=reverse($s)              # mirror
    for 0..1                        # twice
}

$_ = join$/,                        # join using newline
map {                               # iterate the lines
    (' 'x abs($n-$i++-1)) .$_       # prepend padding
} $s=~/\S+/g;                       # match lines

s/\S/ $&/g                          # prepend spaces to characters
                                    # -p takes care of printing $_

update 200 save a byte moving variable assignment, and another 2 by omitting final ;; code itself under 200 bytes now!
update 198 save 2 bytes by using $s=~/\S+/g instead of split/\n/,$s

JavaScript (ES6), 162 172
Anonymous function
The hexagon size is found resolving the equation from wikipedia
3*n*(n-1)-1 = l

The solving formula is basically
n = ceil(3+sqrt(12*l-3))/6)

With some algebra and some approximation (thx to @user18655 too) it becomes
n = trunc(sqrt(l/3-1/12)+1.4999....)

s=>eval("s=s.match(/\\S/g);m=n=Math.sqrt(s.length/3-1/12)+1.49999|0;p=o=``;for(i=n+n;--i;i>n?++m:--m)for(o+=`\n`+` `.repeat(n+n-m),j=m;j--;o+=` `)o+=s[p++]||`.`")

More readable
s=>{
  s=s.match(/\S/g);
  m=n=Math.sqrt(s.length/3-1/12)+1.49999;
  p=o='';
  for(i=n+n; --i; i>n?++m:--m)
    for(o += '\n'+' '.repeat(n+n-m), j=m; j--; o += ' ')
      o+=s[p++]||'.';
  return o
}

Test snippet (better full page - running time ~ 1 minute)

f=s=>eval("s=s.match(/\\S/g);m=n=Math.sqrt(s.length/3-1/12)+1.49999|0;p=o=``;for(i=n+n;--i;i>n?++m:--m)for(o+=`\n`+` `.repeat(n+n-m),j=m;j--;o+=` `)o+=s[p++]||`.`")

t=0;
r='0';
(T=_=>t++<816?(O.innerHTML=f(r=t%10+r),setTimeout(T,20)):0)()
pre { font-size: 66% }
<pre id=O></pre>

You could use n=...+1-1e-9|0 instead of n=Math.ceil(...) to save 2 bytes. You could also go ES7 and use **0.5 instead of Math.sqrt but that's up to you. I usually just keep my answers ES6 because they work in my browser haha!

@user81655 good hint, thanks

Pyth, 52 51 bytes
Jfgh**3TtTl=H-zd1=+H*\.*lHTV+UJt_UJAcH]+JN+*-JNdjdG

Try it online. Test suite.
Each line has one extra leading space, as permitted by the OP.
Explanation
 f              1          |   find first number n for which
             -zd           |           remove spaces from input
           =H              |         put result in H
          l                |       length of input without spaces
  g                        |     is less than or equal to
   h**3TtT                 |       nth centered hexagonal number
J                          | put result (hexagon side length) in J
                           |
      *lHT                 |      ten times length of input without spaces
   *\.                     |   that amount of dots
=+H                        | append to H
                           |
  UJ                       |    numbers 0 up to side length - 1
 +  t_UJ                   |   add numbers side length - 2 down to 0
V                          | loop over result
            +JN            |       current loop number + side length
         cH]               |     split to two parts at that position
        A                  |   put parts to G and H
                 -JN       |       side length - current loop number - 1
                *   d      |     that many spaces
                     jdG   |     join code on the line (G) by spaces
               +           |   concatenate parts and print

Retina, 161 bytes
Thanks to FryAmTheEggman for saving 2 bytes.
This answer is non-competing. Retina has seen a few updates since this challenge, and I'm pretty sure I'm using some of the newer features (although I haven't checked).
Byte count assumes ISO 8859-1 encoding. The first line contains a single space. Note that most of the · are actually centre dots (0xB7).

^
$._$*·¶
^·¶
¶
((^·|\2·)*)·\1{5}·+
$2·
^·*
$.&$* ·$&$&$.&$*
M!&m`(?<=(?= *(·)+)^.*)(?<-1>.)+(?(1)!)|^.+$
+m`^( *·+)· *¶(?=\1)
$&
·
 ·
O$`(·)|\S
$1
·
.
G-2`

Try it online!
Well...
Explanation
It seems easiest to build the layout first using just a single character (· in this case) and then fill the resulting layout with the input characters. The main reasons for this are that using a single character lets me make use of backreferences and character repetition, where laying out the input directly would require expensive balancing groups.

Although it doesn't look like much, this first stages removes spaces from the input.
^
$._$*·¶

We start by prepending an additional line which contains M centre dots, where M is the length of the input (after removing spaces).
^·¶
¶

If the input was a single character, we remove that centre dot again. This is an unfortunate special case that isn't covered by the next stage.
((^·|\2·)*)·\1{5}·+
$2·

This computes the required side length N minus 1. Here is how that works: centred hexagonal numbers are of the form 3*N*(N-1) + 1. Since triangular numbers are N*(N-1)/2, that means hexagonal numbers are six times a triangular number plus 1. That's convenient because matching triangular numbers (which are really just 1 + 2 + 3 + ... + N) in a regex is fairly easy with forward references. The (^·|\2·)* matches the largest triangular number it can. As a nice bonus, $2 will then hold the index of this triangular number. To multiply it by 6, we capture it into group 1 and match it another 5 times. We make sure there are at least two more · with the · and the ·+. This way the index of the found triangular number doesn't increase until there's one character more than a centred hexagonal number.
In the end, this match gives us two less than the side-length of the required hexagon in group $2, so we write that back together with one more centre dot to get N-1.
^·*
$.&$* ·$&$&$.&$*

This turns our string of N-1 centre dots into N-1 spaces, 2N-1 centre dots and another N-1 spaces. Note that this is the maximum indentation, followed by the diameter of the hexagon, followed by the indentation again.
M!&m`(?<=(?= *(·)+)^.*)(?<-1>.)+(?(1)!)|^.+$

This is unpleasantly long, but it basically just gives us all overlapping matches, which are either a) 2N-1 characters long and on the first line or b) the second line. This expands the result from the previous stage into the full, but weirdly indented hexagon. E.g. for input 12345678 we'd get:
  ···
 ····
·····
····
···
12345678

This is why we needed to append spaces in the previous stage as well.
+m`^( *·+)· *¶(?=\1)
$&

This fixes the indentation of the lines after the centre, by repeatedly indenting any line that is shorter than the previous (ignoring trailing spaces), so we get this:
  ···
 ····
·····
 ····
  ···
12345678

Now we just insert some spaces with
·
 ·

Which gives us:
   · · ·
  · · · ·
 · · · · ·
  · · · ·
   · · ·
12345678

Phew, that's done.
O$`(·)|\S
$1

Time to fill the input string into the centre dots. This is done with the help of a sort stage. We match all centre dots and each character on the last line, and we sort them by the result of the given substitution. That substitution is empty for the characters on the last line and · for the centre dots, so what happens is that the centre dots are simply sorted to the end (since sorting is stable). This moves the input characters into place:
   1 2 3
  4 5 6 7
 8 · · · ·
  · · · ·
   · · ·
········

Just two things left now:
·
.

This turns centre dots into regular periods.
G-2`

And this discards the last line.

JavaScript (ES6), 144 bytes
(s,n=1,l=0,p=0,m=s.match(/\S/g))=>m[n]?f(s,n+6*++l,l):[...Array(l+l+1)].map((_,i,a)=>a.map((_,j)=>j<l-i|j<i-l?``:m[p++]||`.`).join` `).join`\n`

Where \n represents the literal newline character. Uses a technique for creating a hexagon that I've previously used on several other hexagonal-grid answers. For ES7 taking square roots works out slightly shorter than the recursive approach:
(s,p=0,m=s.match(/\S/g),l=(~-m.length/3)**.5+.5|0)=>[...Array(l+l+1)].map((_,i,a)=>a.map((_,j)=>j<l-i|j<i-l?``:m[p++]||`.`).join` `).join`\n`

Python 3, 144 bytes
c=input().replace(' ','')
n=x=1
while x<len(c):x+=n*6;n+=1
c=c.ljust(x,'.')
while c:print(' '*(x-n)+' '.join(c[:n]));c=c[n:];n-=(len(c)<x/2)*2-1

Try it online!
This uses a rather varying amount of leading whitespace for different sized hexagons, but the general shape survives.

Nibbles, 27 bytes
+!/|.,~+.,;+-$~$::"\n"`<!=$_^-@~" "`'$~-,;+%_~,@$:@^~".":

That's 54 nibbles, each half a byte in the binary form (the " " and "\n" are only 2 nibbles each).
Run it like this (Nibbles isn't on TIO yet...):
> echo abcdef | nibbles hex.nbl

 a b
c d e
 f .

How?
Rather than compute the smallest centered hexagonal number, calculate the spaces that would be added before each input character for all possible sized hexagons. Find the first one that has as many entries as there are input characters and then just zip them together. This is a good example of the power of laziness, although mainstream languages could have accomplished the same feat with streams/enumerators.
Translation
+                        concat
 !                       zip with
  /                      foldr
   |                     filter
    . ,~                 map [1..] (call it n)
      + . ,              concat map 1 to (call it i)
           ; + -$~ $     n-1+n (saved, call it k)
          :              append
           :"\n"         newline prepended with
            `< != $ _    splitAt abs n-i (returns take part)
               ^ -@~ " " replicate " " k-1 times
           `' $          transpose of the drop part from splitAt
                         below is the fn for filter
    ~ -                  not of difference (aka <=)
        , ; +%_~         length of input with spaces removed via concat words of input (saved)
        , @              length of space table
   $                     fold's element variable (essentially / ... $ is a way to take head of a list)
  :@^~"."                our space removed input with infinite "." added
  :                      append (arg to zip with), combines space table with input

One trick is that newline was prepended to the first space table element on each line, so that the final zip also adds newlines correctly.
Another trick is the realization that each line has 2n-2 spaces. So a take/drop (splitAt) is used to take the number needed before the first of the line and the remainder is all the things needed before each character (transpose is used to convert that to a list of strings instead of just a string).
It seems a little silly to precompute the fact that we need to add a single space to most characters, but doing so is what ultimately enables us to count the size of the hexagon and combine that hexagon with the input trivially.

Knight, 158 152 bytes
;=n~1;=pP;=s'';Wp;=s+sI?32Ap''A Ap=pGp 1Lp;W<+1+**3=n+nTn*3nLsN;=i+1*2nW+1=i-iT;O+*' '=xI>=x-n iFx~x'\';=j~2;W<=j+1j-*2n xIs;O+A As' \'=sGs 1LsO'. \'O''

idek anymore lol
Try It Online!
Test Suite


text:
Symbolic Integration of Polynomials
Apply an indefinite integral to a given string. The only rules you will be using are defined as such:
∫cx^(n)dx = (c/(n+1))x^(n+1) + C, n ≠ -1
c, C, and n are all constants.

Specifications:

You must be able to integrate polynomials with any of the possible features:

A coefficient, possibly a fraction in the format (numerator/denominator).
Recognition that e and π are constants, and in their use, be able to form fractions or expressions containing them (can be held in a fraction like (e/denominator) or (numerator/e), or, if in exponents, x^(e+1))

Aside of these two special constants, all coefficients will be rational, real numbers.

An exponent, possibly a fraction, in the format x^(exponent)

Expressions with e or π in them, aside of themselves, will not be in exponents. (you will not have to integrate stuff like x^(e+1), but you might integrate x^(e))

Can use non-x 1-char variables (i.e. f)

This is only for ASCII ranges 65-90 and 97-122.

You do not have to use chain rule or integrate x^(-1).

Output must have padding (separation between terms, i.e. x^2 + x + C.
If it is unknown how to integrate with the above features, the program should print out "Cannot integrate "+input.
It must be a full program.

Bonuses:

-10% if you print out the "pretty" exponents formatted for markdown (instead of x^2, x2).
-10% if you print out the equation (i.e. ∫xdx = (1/2)x^2 + C)

Examples:
Input:
x
Output:
(1/2)x^(2) + C

Input:
-f^(-2)
Output:
f^(-1) + C

Input:
(1/7)x^(1/7) + 5
Output:
(1/56)x^(8/7) + 5x + C

Input:
πx^e
Output:
(π/(e+1))x^(e+1) + C

Input:
(f+1)^(-1)
Output:
Cannot integrate (f+1)^(-1)

Surprised we don't already have this question - but I couldn't find a dup. +1

@DigitalTrauma There is this, though.

I presume that other than e and π, the only values in coefficients will be rational numbers? I.e. it's not necessary to handle multivariable polynomials? 2. When you say "non-x 1-char variables", are you restricting to a-zA-Z or do you intend to include other Unicode ranges?

Dang, I was going to post this at some point. Oh well.

Do you think there should be a bonus if someone's program prints ln(x) + C for an input of x^(-1)?

@Ampora No - that opens up a whole can of worms dealing with coefficients of ln.

Do you really need to print a 27-char string Cannot integrate polynomial?

@xnor Cannot integrate , and yes.

What would πe integrate as? Would e be considered as exp(1), or as a variable? If the former, would we assume x to be the variable?

@TomCarpenter πe would integrate as a constant, so it would integrate to (πe)x. I wouldn't make a coefficient this complicated, so you may assume that this will be an untested input.

How are we supposed to solve the halting problem?

@FlagAsSpam I misread your question. For the general case, computing integrals involves solving the halting problem since e^(ax^2) is integrable if and only if a is always 0, but being able to show that is equal to the halting problem.

So it is necessary for it to only solve the polynomial integrals? Are built-ins allowed?

@TanMath Yes and yes, but make sure you do output "Cannot integrate " for things that are more difficult than just power rule.

a few questions for clarification:
x^(e+1) is given as an example of how transcendentals may appear in an exponent, but also as an example of how they won't. -> !?
Also, could there ever be multiple letter variables, if so how to choose which to integrate over? May we use pi or p for π?
Lastly, is the output supposed to be concise, and if so how is that defined? f.x. is (1/7)x^(1/7) to (1/8)x^(1/7+1) + C ok?

@LeifWillerts 1) I meant that x^(e+1) will not be an integrand, but it may be the result of an integration. 2) There will not be multiple letter variables. 3) Yes. 4) Yes, but it should be (1/56)x^(1/7+1) + C (I made a mistake in the examples).

Now that I can comment: I assumed that C is also not going to be an input variable but reserved for the integration constant. Otherwise, of course, this would need to be clarified and the code changed accordingly.

@senegrom Yes, that's correct. c: Nice answer, btw.

Mathematica 478 * 0.9 = 430.2
φ=(α=ToExpression;Π=StringReplace;σ="Cannot integrate "<>#1;Λ=DeleteDuplicates@StringCases[#1,RegularExpression["[a-df-zA-Z]+"]];μ=Length@Λ;If[μ>1,σ,If[μ<1,Λ="x",Λ=Λ[[1]]];Ψ=α@Π[#1,{"e"->" E ","π"->" π "}];Φ=α@Λ;Θ=α@Π[#1,{"e"->" 2 ","π"->" 2 "}];λ=Exponent[Θ,Φ,List];Θ=Simplify[Θ*Φ^Max@@Abs@λ];Θ=PowerExpand[Θ/.Φ->Φ^LCM@@Denominator@λ];If[Coefficient[Ψ,Φ,-1]==0&&PolynomialQ[Θ,Φ],"∫("<>#1<>")d"<>Λ<>" = "<>Π[ToString[Integrate[Ψ,Φ],InputForm],{"E"->"e","Pi"->"π"}]<>" + C",σ]])&

This creates a true function φ that takes one String as Input.
(Does that count as complete program for Mathematica?)
The ungolfed version would be:
φ=(
    σ="Cannot integrate "<>#1;
    Λ=DeleteDuplicates@StringCases[#1,RegularExpression["[a-df-zA-Z]+"]];
    If[Length@Λ>1,σ,
        If[Length@Λ<1,Λ="x",Λ=Λ[[1]]];
        Ψ=ToExpression@StringReplace[#1,{"e"->" E ","π"->" π "}];
        Φ=ToExpression@Λ;
        Θ=ToExpression@StringReplace[#1,{"e"->" 2 ","π"->" 2 "}];
        λ=Exponent[Θ,Φ,List];
        Θ=Simplify[Θ*Φ^Max@@Abs@λ];
        Θ=PowerExpand[Θ/.Φ->Φ^LCM@@Denominator@λ];
        If[Coefficient[Ψ,Φ,-1]==0&&PolynomialQ[Θ,Φ],
            "∫("<>#1<>")d"<>Λ<>" = "<>StringReplace[ToString[Integrate[Ψ,Φ],InputForm],{"E"->"e","Pi"->"π"}]<>" + C",
            σ
        ]
    ]
)&

Note that the Greek letters are necessary to be able to use all the other letters in the input.

MATLAB, 646 x 0.9 = 581.4 bytes
t=input('','s');p=char(960);s=regexprep(t,{p,'pi([a-zA-Z])','([a-zA-Z])pi','([\)e\d])([a-zA-Z])','([a-zA-Z])(([\(\d]|pi))','e^(\(.+?\))','e'},{'pi','pi*$1','$1*pi','$1*$2','$1*$2','exp($1)','exp(1)'});r=[s(regexp(s,'\<[a-zA-Z]\>')),'x'];r=r(1);e=0;try
I=int(sym(strsplit(s,' + ')),r);S=[];for i=I
S=[S char(i) ' + '];end
b=0;o=[];for i=1:nnz(S)
c=S(i);b=b+(c==40)-(c==41);if(c==42&&S(i+1)==r)||(b&&c==32)
c='';end
o=[o c];end
o=regexprep(char([8747 40 t ')d' r ' = ' o 67]),{'pi','exp\(1\)','exp','\^([^\(])',['1/' r]},{p,'e','e^','^($1)',[r '^(-1)']});catch
e=1;end
if e||~isempty(strfind(o,'log'))
disp(['Cannot integrate ' t]);else
disp(o);end

This is currently a work-in-progress using MATLABs built in symbolic integration capabilities. Currently the requirements have been updated so the format now matches the requirements. It also does qualify for the second -10% bonus.
If anyone wants to pitch in and suggest ways of correcting the output, or use this code as a basis for another answer, feel free :). If I can find the time, I'll keep playing with it and see if I can think how to reformat the output.
Update: Ok, so after a bit more work, here is how the code currently stands. It is still a work in progress, but now getting closer to matching the required output.
t=input('','s'); %Get input as a string
p=char(960); %Pi character
s=regexprep(t,{p,'pi([a-zA-Z])','([a-zA-Z])pi','([\)e\d])([a-zA-Z])','([a-zA-Z])(([\(\d]|pi))','e^(\(.+?\))','e'},{'pi','pi*$1','$1*pi','$1*$2','$1*$2','exp($1)','exp(1)'}); %Reformat input to work with built in symbolic integration
r=[s(regexp(s,'\<[a-zA-Z]\>')),'x'];r=r(1); %determine the variable we are integrating
e=0; %Assume success
try
    I=int(sym(strsplit(s,' + ')),r); %Integrate each term seperately to avoid unwanted simplificaiton
    S=[];
    for i=I
        S=[S char(i) ' + ']; %Recombine integrated terms
    end
    %Now postprocess the output to try and match the requirements
    b=0;o=[];
    for i=1:nnz(S)
        %Work through the integrated string character by character
        c=S(i);
        b=b+(c=='(')-(c==')'); %Keep track of how many layers deep of brackets we are in
        if(c=='*'&&S(i+1)==r)||(b&&c==' ') %If a '*' sign preceeds a variable. Also deblank string.
            c=''; %Delete this character
        end
        o=[o c]; %merge into new output string.
    end
    o=regexprep([char(8747) '(' t ')d' r ' = ' o 'C'],{'pi','exp\(1\)','exp','\^([^\(])',['1/' r]},{p,'e','e^','^($1)',[r '^(-1)']});
catch
    e=1; %failed to integrate
end
if e||~isempty(strfind(o,'log'))
    disp(['Cannot integrate ' t])  %bit of a hack - matlab can integrate 1/x, so if we get a log, we pretend it didn't work.
else
    disp(o)% Display it.
end

Here are some examples of what it currently produces. As you can see, it's not quite right, but getting closer.
Inputs:
x
-f^(-2)
(1/7)x^(1/7) + 5
πx^e
(f+1)^(-1)

Outputs:
∫(x)dx = x^(2)/2 + C
∫(-f^(-2))df = f^(-1) + C
∫((1/7)x^(1/7) + 5)dx = x^(8/7)/8 + 5x + C
∫(πx^(e))dx = (πx^(e+1))/(e+1) + C
Cannot integrate (f+1)^(-1)

I assume the problem with output that you're having is that the fractions don't simplify/go into a single coefficient?

@FlagAsSpam, the fractions are simplifying, but the trouble is they end up on the wrong side of the variable. For instance in the third example it results in x^(8/7)/8 which while mathematically correct is not in the form you want it - (1/8)x^(8/7).

Considering that you are the only answer so far, I might consider changing that if no more answers come through in a day or two to "any mathematically correct, valid output" for fractions.

Your answer is valid - You do not have to simplify fractional output anymore. c:

I will golf it down a bit then and count the bytes.

Can you use ||nnz() instead of ~isempty(). Also, I think you can use |instead of||, since e` is a scalar...

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Center The Text!
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="
"+e.body.replace(OVERRIDE_REG,"")+"
")});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;/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}
 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

This is code-golf so shortest code in bytes wins!

There will never be more than one inner-space?

@cat there will never be any leading whitespace or trailing whitespace on a line (expect for the newline if there is one)

yes, but I mean inner-spaces, like, between words

@cat oh, between words there may be more than one whitespace. For example foo(space)(space)(space)bar is a perfectly acceptable input

can we assume there will always be more than 1 line?

@GamrCorps I'd say no, your program should still work even if only one line is given as input.

What about trailing spaces? Forbidden, optional, or mandatory?

@Timwi I'll say trailing/leading whitespace isn't allowed.

I'm not sure you mean when you say you don't want leading whitespace in the output. The first line in your output example " Foo" has a leading whitespace.

@Willem I meant additional leading newlines added by the program, I've clarified

@Downgoat I think if you edit your question Specifications by replacing "Each line" by "Each input line" that will clarify things.

OK, glad you clarified that, however you should be aware that this renders most of the existing answers invalid.

Pyth, 19 17 bytes
2 bytes thanks to Jakube
V.ztr+1.[l.T.zNd6

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

We probably need a max length in array. It comes up way too often. +1

The specifications say that "Trailing whitespace in the output is not allowed."  This appears to have trailing whitespace on each short line in the output, so I'm not sure it counts.

@potato Thanks - that was added since I answered.

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

Surely this should all be done in Insert mode, right?

@AlexA. None of it is done in insert mode. ಠ_ಠ

If you use sor! to reverse the sort order, you can use col("$") to get the length of the first line (now the longest since the order is reversed) instead of using G$, saving a grand total of 1 byte! edit: or you could keep the sort order and use G:let &tw=col("$") instead.

@Marth Thanks! I chose the latter (for no particular reason).

Looking through :h :sort I just found out that you can pass a regex to skip the matching text in the sort, so you can use :sor /./ to sort on length (+4 bytes), which lets you remove the VGrx (-4 bytes) and the second undo (-1 bytes). You can also use | separators instead of <cr> to chain the commands, which lets you skip the : before let (-1 bytes) (note that you have to use the sor! solution then, G is not an ex command). So :sor! /./|let &tw=col("$")|u|%ce  (with a trailing <CR>) should save 2 bytes.

@Marth Alas, :sor! /./ does not seem to be sorting by length, like you said it should.

@Doorknob冰: Erf, you're right. I could have sworn it worked when I tried it, but you need to use :sor /.*/ for it to work, which means it doesn't save any byte… oh well

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.

+1 for "Don't ask me how it worked, I just fiddled with it until it produced the correct output"

@cat That's how I do all my golfing.

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.

+1 for how awesome this is and "That’s 716 characters, totaling 1,508 bytes"

Retina, 54 52 bytes
+m`^(.)+$(?<=(?=[^\t]*^..(?<-1>.)+(?(1)^))[^\t]*)
 $0

The \ts 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.
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.

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

Here are some suggestions :) qN/_z,f{1$,m2/S*\N}

Jolf, 3 bytes
Noncompeting, update postdates question.
Try it here!.
pci
pc  center
  i  string input

¯\_(ツ)_/¯ I thought it'd be a useful function.

This is a standard loophole, and while not explicitly dis-allowed, its bad form unless its built into a language you find, not one you create.

@EliasBenevedes I added the feature before the contest. I don't often update my code until it becomes relavent.

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

<button onclick="result.textContent=solution(input.value)">Go</button>

.repeat accepts and truncates non-integer values, so you don't need |0

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

It doesn't save chars to assign len to a variable you use twice -- that breaks even at 5 chars (like range). Also, you can use map for the list comp.

@Willem, you could use str.rstrip() after calling center to get rid of the trailing space.

You can save 7 bytes with a full program and using len(max(a,key=len)), see this.

LabVIEW, 3 or 35 LabVIEW Primitives
Finds lines until none are left, then calculates how many spaces to add and puts everything together.

Alternatively you could use the built-in center alignment on string indicators, it kinda does feel like cheating though.

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

Why do my answers keep getting Downgoated? I think it's time to change the username / avatar :p

Fixed as of 2016-07-27. :P

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.

you can use Shortening Property Names and Length of elements to get 58 bytes

@mazzy that is better! since you didn't post as an answer, I've edited that into my answer with credit.

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

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

53 bytes: ->t{(s=t.split$/).map{|l|l.center s.map(&:size).max}}

I also tried the center way first, but as I understand, that alone would break the “Trailing whitespace in the output is not allowed” rule. Thank you for the &:size part – I also tried that too, but I certainly banged something around the syntax.

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.

Whoa, xmp is HTML 2.0, that’s dinosaur technology. It’s funny that you’re using style that wasn’t an attribute until HTML 4.0, though. I wonder how HTML can be an (upvoted) eligible submission. It’s a markup language; you know, there is no input/output facility.

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 for 34 bytes, great job! :D

Two more things: The latest version of the Prelude includes an infix version of map: <$>. replicate(...)' ' can be replaced by [1.. ...]>>" ". All in all: unlines[([1..div(maximum(l<$>q)-l w)2]>>" ")++w|w<-q].

Ah yes I remember you mentioning the new map infix in a previous submission I made. How does the replicate trick work?

l1 >> l2 makes (length l1) copies of l2 and concatenates them. E.g. "abcd" >> [1,2] -> [1,2,1,2,1,2,1,2] (<- 4 copies of 1,2 in a single list). In our case it's [1..n]>>" " which is n copies of a space which is the same as what replicate does.

Nice, thanks for the explanation! :)

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

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.

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

Perl 6, 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

Perl 5 would allow you to drop the spaces in things like for @l {, shaving 2 bytes, and to change put " " to put" ", shaving another byte. Is that true for Perl 6? (I don't know Perl 6.) Also, your output as displayed here doesn't match the required output; is that a typo?

@msh210 Perl 6 is a bit more restrictive with its syntax. It more than makes up for it in other areas though.

Japt, 28 25
¡V=VwXl}R;¡Sp½*(V-Xl¹+X}R

Try it online!
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.

05AB1E, 2 bytes
.c

Builtins ftw ¯\_(ツ)_/¯
Try it online or verify all test cases.
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.)

PHP, 98 bytes
function($s){foreach($a=explode("
",$s)as$l)echo str_pad($l,max(array_map(strlen,$a)),' ',2),"
";}

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

Japt, 1 byte
û

Try it or run all test cases

why was this at -1 votes lol

APL (Dyalog 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!
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

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.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Russian Roulette, Reloaded
Let's play Russian Roulette!
Normally, this would be a race to write the shortest MOD 6 program, but that's not very realistic, as the chance of winning decreases with each click. Here are the rules:

Emulate a real six-shooter:

A single bullet is placed into one of the six chambers, and the barrel is spun once, only before playing.
The chance of losing on the nth try is 1/6.
The chance of losing after n tries is 1/(6-n)
You are guaranteed to lose in, at most, 6 tries.

Losing:

Display the text *BANG!*
Terminate the program.

Winning:

"Winning" means the gun does not fire, but the bullet is one chamber closer to the hammer.
Display the text *click*
Present a "trigger" to the user, along with the ability to terminate the program (e.g. "ctrl+c", see below).

Program specific:

Pulling the trigger is some form of user input, including the first try. (This can be a keystroke, a mouse click, whatever; text prompts are not required.)
Only one instance of the program is allowed until it is terminated. (Running a new instance of the program is akin to giving the barrel a good spin, i.e. the probability of losing on the next click is reset to 1/6.)

Shortest code wins!
Leaderboard

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

I'm unclear on the probabilities. Is the loss time uniformly distributed between 1 and 6?

@xnor The probability of losing on the nth try is 1/6 - however, the probability of losing after n tries is 1/(6-n), since the probability of firing a bullet reaches one as the number of remaining empty chambers reaches zero.

This is very hard to do nondeterministically, I find.

Your assumptions are wrong - the chance of losing on the n'th try is only ⅙ if you respin the bullets after each shot. Without respinning the chance of losing is ⅙ on the first shot, ⅕ on the second, ¼ on the third... ending in 1 on the 6th. You recognise this with "You are guaranteed to lose in, at most, 6 tries".

@user2956063 you are forgetting that there is a (n-1)/6 chance that you never reach the n:th try, and thus cannot lose. They balance out to a uniform 1/6.

maybe that's a difference in the way computer scientists and statisticians express probability then - to me "The chance of losing on the nth try is ⅙" say's it's constant - whether n is 1 or 100.

Why was this not titled "Russian Roulette, Reloaded"?

@Hand-E-Food Because I'm not very creative, especially with titles :P

I posted my answer several hours ago and I only just got the title now. well done (or I might just be stupid—that's never outside of the realm of possibility)

@user2956063: Your probabilities are conditional. P(lose on shot 2) = ⅙, but P(lose on shot 2 | didn't lose on shot 1) = ⅕. Also, n is (implicitly, I'll grant you) limited to [1,6], so 100 is out.

Pyth, 23 bytes
VO6"*click*" w;"*BANG!*

Really simple. A random number of iterations 0 - 5 display click and request a line of input, followed by a bang at the end.

damn you, pyth!

+3 bytes: the last string should be *BANG!*, not BANG

Ruby, 51 bytes
[*['*click*']*rand(6),'*BANG!*'].map{|x|gets;$><<x}

Ungolfed:
[
  *(                        # Unwrap the following array into the outer one
    ['*click*'] * rand(6)   # An array of 0-5 clicks, see Array#*
  ),
  '*BANG!*'                 # The End
].map do |x| # Shortest way to iterate I was able to find
  gets       # Await input
  $> << x    # Shove the output string to `stdout`
end          # Return value is an array of several (0-5) `stdout`s. Who cares.

or
(['*click*']*rand(6)<<'*BANG!*').map{|x|gets;$><<x}

Ungolfing left for the readers. Not that difficult

Again, kudos to Martin, this time for a trick with $><< as a puts replacement.
Doesn't output newlines, but that was not required.
The shorter, the simpler. The gist of the required behaviour is to do 0-5 clicks and then fire. For that, outputs are accumulated inside the array.
2 more bytes can be shaved off if outputs like "*click*" are okay (what's required is printed in the end), by replacing $><< with p . I wasn't sure if this would still follow the rules.

68 64 bytes
(another approach)
[*0..5].shuffle.find{|x|gets;x<1||puts('*click*')};puts'*BANG!*'

Kudos to Martin Büttner for -4 extra bytes.

I didn't put much thought into the algorithm (it can possibly be even more compact, but not so clear), but I really like the model inside it:

An array emulates a barrel with its elements being chambers' contents. Since only one element is a bullet, rotating it and shuffling it are equivalent.
0 is a bullet. Other numbers are not.
find finds a first return value for which the block is neither false nor nil.
||-expression is implicitly returned from the block. It's a short-circuit: it returns its first operand (unless it's nil or false) or a second one (otherwise). So it either returns true (if x<1 or, clearer but longer x == 0) or the return value of puts, while...
puts always returns nil. Yep.
gets requests input. Merely hitting Enter suffices.
Ctrl+C terminates the program

Crossed out 64 is normal 64?

@Cyoce uhm... yes. Should be, probably. It's been superceded by the above entry, but it is based on a different idea, so I left them, crossed out.

it was a pun on this

@Cyoce oh, pardon me, first post and all that, not aware of the local lore :)

JavaScript, 64 bytes
for(i=6;i<7&&prompt();)alert(new Date%i--?"*click*":i="*BANG!*")

Explanation
To pull the trigger enter any text into the prompt. Enter nothing or click cancel to terminate.
for(
  i=6;             // i = number of chambers
  i<7              // i equals "*BANG!*" (not less than 7) if we lost
    &&prompt();    // see if we should do another shot
)
  alert(           // alert the result
    new Date%i--   // use the current time in milliseconds as a random number, this is safe
                   //     to use because the gap between shots is greater than i (max 6ms)
      ?"*click*"   // on win pass "*click*" to alert
      :i="*BANG!*" // on lose alert "*BANG!*" and set i to not less than 7
  )

"*Bang!*" is not greater than 7. But NaN is not smaller than 7.

@Bergi That's true. I reworded the explanation to make it a bit clearer.

@Bergi only in Javascript does that statement come even close to making sense.

Lua, 82 75 bytes
Pretty long, but there's lot of verbose in lua.
for a=math.random(6),1,-1 do io.read()print(a>1 and"*click*"or"*BANG!*")end

LabVIEW, 46 LabVIEW Primitives
Creates an Array of 0s and one 1, has a loop to wait for clicks and outputs the string. It initially says BANG becuase i forgot to reset the indicator before starting it.
Also note that this is a gif, if if does not play/load for you please reopen the page.

I don't see where you do the output of "*click*" in case the gun didn't shoot. Also, does it output "bang" or "*BANG!*"?

this should be a gif but for me it doesnt play, that might be the problem. And yes it only puts bang, that was me not reading properly i change that in a sec

stupid me forgot to reinitialize the string to empty before starting so thats why it showes BANG at the start...

No problem, I saw the gif now, looks like it works pretty well :)

Pyth, 31 30 28 bytes
FN.S6 EI!N"*BANG!*"B"*click*

Almost certainly can be improved. Input any number to pull the trigger, blank input to terminate early (with an error).
Explanation:
FN                               for N in...
  .S6                            shuffle(range(6))...
      E                          get a line of input
       I!N                       if N is falsy (i.e. 0)
          "*BANG!*"              implicit output
                   B             break
                    "*click*     else, print click

Your first one is actually shorter, you don't need the trailing".

@FryAmTheEggman Oh, right, forgot about that. Thanks!

Also, I've just noticed something silly, FN<any> is still entirely identical to V<any>, that should probably be changed to not confuse new golfers... :P

You can simply remove the chars .?. There is no need for an else.

@FryAmTheEggman confusing people is awesome. It can be amazing at filtering out the scrubs.

Seriously, 27 25 bytes
"*BANG!*"6J"*click*"nW,X.

No online link because there is no way to do a prompt with piped input. The program can be CTRL-C'd at any time to chicken out terminate.
Explanation:
"*BANG!*"6J"*click*"nW,X.
"*BANG!*"                  push "*BANG!*"
         6J                push a random integer in [0,6) (n)
           "*click*"n      push "*click*" n times
                     W     while loop (implicitly closed at EOF):
                      ,X.    get input and discard, pop and print top of stack

Perl 5, 43 bytes
Run with perl -p. Stable bullet variant - i.e. bullet position is decided only once in very beginning.
$i//=0|rand 6;$_=$i--?'*click*':die'*BANG*'

Nice! I would change the header to "Perl 5.10+", since you're using //=. Also, don't forget to count -p in your score.

PHP, 52 bytes
*<?=$n=&rand(0,6-$argi)?click:"BANG!*";$n||@\n?>*

Requires the -F command line option, counted as three. The trigger is pulled by pressing Enter.
Because -F literally runs the script again for every input (I kid you not), die and the like won't actually terminate, so we exit via suppressed runtime error instead, @\n.

Sample Usage
$ php -F primo-roulette.php

*click*
*click*
*BANG!*
$

C, 110 74 72 bytes
Thanks to Dennis for getting rid of the includes and a lot less bytes.
main(r){for(r=time(0)%6;getchar(),r--;)puts("*click*");puts("*BANG!*");}

main(r)
{
    for(r=time(0)%6;getchar(),r--;)
        puts("*click*");
    puts("*BANG!*");
}

Candy, 36 bytes
About half the program is the text to print out :(
:6H_(=b"*click*"(;):=)"*BANG!*\n"(;)

long form:
getc
digit6 rand range0  # build a range from 0 .. rand#
while
  popA              # these are the *click* instances
  stack2
  "*click*"
  while
    printChr
  endwhile
  getc
  popA
endwhile
"*BANG!*\n"         # out of luck
while
  printChr
endwhile

PlatyPar, 26 25 bytes
6#?;wT"*click*"O;"*BANG!*

Explanation:
6#?;                        ## random integer [0,6)
    w           ;           ## while stack.last
     T                      ## stack.last--
      "*click*"O            ## alert "*click*"
                 "*BANG!*   ## alert "*BANG!*"

Try it online!

Python, 81 Bytes
import time
for i in["*click*"]*(int(time.time())%6)+["*BANG!*"]:input();print(i)

inspired by the Ruby(51) and Python solutions

Emacs Lisp, 94 89 bytes
(set'b(%(random)6))(dotimes(a(+ b 1))(read-string"")(message(if(eq a b)"BANG""*click*")))

Ungolfed:
(set 'b (% (random) 6))
(dotimes (a (+ b 1))
  (read-string"")
  (message (if (eq a b) "BANG" "*click*")))

R, 86 80 77 bytes
As usual, R has awesome features to code golfing but looooooong function names.
sapply(sample(0:5),function(n){!n&&{cat('*BANG!*');q()};readline('*click*')})

Python 2, 108 104 102 100 98 bytes
My first attempt at golfing:
from random import*
a=[1]+[0]*5
shuffle(a)
for i in a:input();print("*click*","*BANG!*")[i];" "[i]

Maybe I should add that the program doesn't terminate correctly when you lose, it just throws an exception (which results in termination):
Traceback (most recent call last):
  File "russian_roulette.py", line 4, in <module>
    for i in a:input();print("*click*","*BANG!*")[i];" "[i]
IndexError: string index out of range

Welcome to Programming Puzzles & Code Golf! When you post a code golf answer, please include the language name and the byte count (I edited it in for you here). Thanks!

Yes, thanks a lot! I was actually trying to resolve that issue, didn't get to edit it correctly before you did.

I get your byte count as 112, what did you use?

Also, you can save 2 bytes by doing a=shuffle([1,0,0,0,0,0])

As far as I know shuffle changes the underlying data structure and doesn't return anything. I tried that, thanks anyways. The headline (language and byte count) was written by ProgramFOX. But when I use wc it gives me 109 which one too much, so it's right. How do you count?

Why do you need [(i^1)] ? can't you just put [i] and invert BANG and click? Like this: print(("*click*","*BANG!*")[i])

I tested it and it seems to work. Do you mean the exception raised by " "[i] when i = 1? I believe my hint doesn't change this behavior.

Ah, I see you've changed it :) Also if you change from python 3 to python 2 you can get rid of the print parenthesis.

@Boomerang Thanks and sorry for the confusion.. It works as you said! I was thinking about flipping the bits in the vector (I tried that earlier). I adjusted the code.

@Boomerang Yes, I know. But then again, how does input() not give an EOF error in python2? Because raw_input() is too long.

Look at my solution for python 2 ^^ The problem says you can use whatever input. My solution requires the user to input "i" before pressing Enter

Python 3, 95 bytes
Also my first golf attempt, also in Python 3. I swear Bruce and I aren't the same person.
from random import*
for a in range(randint(0,5)):input();print("*click*")
input();print("*bang*")

Ungolfed:
from random import*
for a in range(randint(0,5)):
    input()
    print("*click*")
input()
print("*bang*")

Generate a random number between 0 and 5 inclusive, print click that many times, then print bang. Press enter/return to pull the trigger.

Following Bruce's example, you can save a few bytes with from random import*

Unless there's something else I'm missing, it's one byte of savings. But I'll take it! Thanks!

Nice attempt, I used your solution as an inspiration for my python 2 solution ^^

Perl 5, 40 bytes
<>,print"*$_*"for(click)x rand 5,'BANG!'

Run without command line options, the trigger is pulled by pressing Enter.

C, 96 bytes (Without counting comment)
#define R 4//chosen by playing russian roulette, guaranteed to be random
int main(){for(;c++<R&&puts(c<R?"Fire?":"☠Bang!☠");getchar(),puts("*click*"));}

Formatted :
#define R 4 // chosen by playing russian roulette, guaranteed to be random
int main(int c) {
    for( ; c++ < R && puts(c < R ? "Fire?" : "☠Bang!☠") ; getchar(), puts("*click*") );
}

Explanation :
There also is a click when it fires, that's the sound of the hammer being released.
After the bang you need to hit enter to take the gun out of the dead man's hand, rigor mortis squeezed his finger around the trigger.
While you are prying his hand open you hear another click as the trigger snaps back into normal position.

Common Lisp, 109
(do(g(b(nthcdr(random 6)#1='(t()()()()() . #1#))))(g)(read-char)(princ(if(setf g(pop b))"*BANG!*""*click*")))

Not very competitive, but I like circular lists:
(do (;; auxiliary variable x
     x
     ;; initialize infinite barrel, rotate randomly
     (b (nthcdr (random 6) #1='(t()()()()() . #1#))))

    ;; we end the loop when x is T (a bullet is fired)
    (x)

  ;; press enter to shoot
  (read-char)

  ;; pop from b, which makes b advance down the list. The popped value
  ;; goes into x and is used to select the appropriate string for
  ;; printing.
  (princ
   (if (setf x(pop b))
       "*BANG!*"
       "*click*")))

Perl 5, 43 bytes
42 bytes + -p command line option. Just press enter to trigger.
$_=0|rand 7-$.<++$i?die"*BANG!*":"*click*"

Thanks to Dom Hastings for his help! Original answer was 67 bytes:
$i++;$a=$i>=int(rand(6));print$_=$a?'*BANG!*':'*click*';last if($a)

Actually the problem with -p was that it would exit before calling the last print statement, not sure why. I've tried it. Other than that, awesome suggestions, thanks! My knowledge continues to grow...

@DomHastings Also, unfortunately, for some reason the 0| trick didn't work as expected, but I did shave some bytes off of it, the print statement and the last statement like you suggested. How does it look now?

@DomHastings Damn, you are good. I recommend putting that as your own answer, since you definitely wrote a smaller program than I (you have 40 bytes compared to my original 67!)

I appreciate the explanation! Always happy to learn more of my favorite scripting language! I never even knew about the prefex incrementing, that's pretty awesome. Thanks :)

You're very welcome, glad to have helped!

It seems to violate 'The chance of losing after n tries is 1/(6-n)' rule.

I'm not sure I understand you. The specified rule is merely a mathematical reality; the odds of you being shot on the first attempt, which is "after 0 tries" since you haven't tried  yet, is 1/(6-0) or 1/6. The program clearly offers a 1/6 chance of you dying on the first attempt (this is rather macabre, isn't it?)
The "rule" is essentially only actually stating, that we must use a random number generator in our code somewhere. This is adhered to.

@Codefun64 When $i is 2, you will have a 1/3 chance of dying (2/6), rather than 1/5 as it should be. rand 6-$. would solve it.

For example after you fired 4 shots, your 5th should be exactly 1/(6-4) - 50% of dying. This program does not follow this rule.

@primo isn't it 7-$.?

@OlegV.Volkov yes, it is.

Interesting - I edited the post. I will take another look at this when I get some rest.

There no need for the <++$i. 0|rand 7-$. gives you one in six, then one in five, etc.

I thought there was something off, but I'm so sleep deprived right now I couldn't recognize it. I got suspicious when I ran it like 20 times and never got past 4 shots. Will edit in a moment.

MATL, 41 bytes
6Yr`j?t@=?'*BANG!*'DT.}'*click*'DT]}T.]]x

To pull the trigger, input a non-empty string (such as 'try').
To terminate, input an empty string
Examples
In this case the trigger was pulled once and... bad luck:
>> matl
 > 6Yr`j?t@=?'*BANG!*'DT.}'*click*'DT]}T.]]x
 >
> try
*BANG!*

In this case the user stopped (note the final empty input) after two lucky pulls:
>> matl
 > 6Yr`j?t@=?'*BANG!*'DT.}'*click*'DT]}T.]]x
 >
> try
*click*
> try
*click*
>

Explanation
6Yr                  % random avlue from 1 to 6
`                    % do...while
  j                  % input string
  ?                  % if nonempty
    t                % duplicate the orignal random value
    @                % loop iteration index
    =                % are the equal?
    ?                % if so
      '*BANG!*'D     % display string
      T.             % unconditional break
    }                % else
      '*click*'D     % display string
      T              % true value, to go on with do...while loop
    ]                % end if
  }                  % else
    T.               % unconditional break
  ]                  % end
]                    % end
x                    % delete original random value

Python 2, 88 84 bytes
This solution is inspired by the python 3 solutions already given. I chose python 2 to remove the print parenthesis even though this changes the behavior of input().
import time
for i in[0]*int(time.time()%6)+[1]:input();print("*click*","*BANG!*")[i]

I am using modulo of the time as a random function (good enough for russian roulette)
the player input should be "i" then Enter (otherwise input() will throw an error), this trick relies on the fact that the input can be "whatever".

Perl 6,  58   53 bytes

for ^6 .pick(*) {get;say <*BANG!* *click*>[?$_];!$_&&last} # 58 bytes

$ perl6 -pe '$///=^6 .pick;$_=$/--??"*click*"!!say("BANG!")&&last' # 52+1= 53 bytes

Press enter to pull the trigger, or ctrl+c to put it down.

Perl 5, 69 51 49 bytes
map{<>;print"*click*"}1..rand 6;<>;print"*BANG!*"

There is probably some more golfing potential, I will look into this.
Changes:

Saved 8 bytes by removing $l and some semicolons, and 10 bytes by changing <STDIN> to <>
Saved 2 bytes thanks to Oleg V. Volkov

49: map{<>;print"*click*"}1..rand 6;<>;print"*BANG!*"

@OlegV.Volkov Thanks! I'll edit it in now.

Ruby, 45+1=46
Not as clever as D-side's but slightly shorter.
With command-line flag p, run
rand(7-$.)<1?(puts'*BANG*';exit):$_='*click*'

The user can pull the trigger with return and leave with control-c. p causes the program to run in a loop, reading lines from STDIN and outputting $_. Each time it runs, it increments $.. So on the first run, it chooses a random positive integer less than 6, then 5, then 4, and so on. On the first 0, we output manually and exit, until then we output implicitly.
(and now I notice that there's already a very similar Perl. Oh well.)

 VBA, 126 bytes
Golf Version for Minimal Bytes
Sub S()
r=Int(5*Rnd())
e:
a=MsgBox("")
If a=1 Then: If i=r Then MsgBox "*BANG!*" Else: MsgBox "*click*": i=i+1: GoTo e
End Sub

Fun Version that Makes The Buttons more Clear for Increased User Acceptance.
Sub RR()
r = Int(5 * Rnd())
e:
a = MsgBox("Are you Feeling Lucky?", 4)
If a=6 Then: If i=r Then MsgBox "*BANG!*", 16 Else: MsgBox "*click*", 48: i=i+1: GoTo e
End Sub

Some Fun with Custom Forms and You could make a pretty Slick Game in VBA.

APL, 39/65 bytes
{⍞⊢↑⍵:⍞←'*BANG*'⋄∇1↓⍵⊣⍞←'*click*'}6=6?6

Pretty straightforward answer.

What do the two byte counts mean?

C, 180 Bytes
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(){srand(time(NULL));int r,i=6;while(i!=1){getchar();r=rand()%i;if(r){puts("CLICK");}else{puts("BANG");exit(0);}i--;}}

My first attempt at code golf, there's probably a lot of room for improvement :)

Julia, 71 bytes
b=rand(1:6);while b>0 readline();print(b>1?"*click*":"*BANG!*");b-=1end

Press Enter to fire or Ctrl+C to quit. The latter ends with an InterruptException.
Ungolfed:
# Set an initial bullet location
b = rand(1:6)

while b > 0
    # Read user input
    readline()

    # Check the location
    if b > 1
        print("*click*")
    else
        print("*BANG!*")
    end

    b -= 1
end

Lua, 73 bytes
q=io.read q()for i=2,math.random(6)do print"*click*"q()end print"*BANG!*"

R, 79 bytes
code
readline();for(n in 6:1)ifelse(1/n>=runif(1),cat("*Bang*"),readline("*click*"))

ungolfed
readline()                    # Waits for user to press [Enter] if [Esc] is pressed exits
for(n in 6:1) {               # for n=6 to n=1
  ifelse(1/n >= runif(1),     # if 1/n >= a random float from 0 to 1 (uniform dist)
     cat("*Bang*"),           # *You're dead*
     readline("*click*")    # else you have another chance, waits for [Enter] again
  )
}

The program will wait for an [Enter] before every try, if the user press [Esc] instead the program will end. If the *Bang* happens the program will print it and throw an error, thus terminating itself (is this correct?).