[Question]
  [
Alice is an intern in a company that uses Brainfuck as a primary language for both client-side and server-side development. Alice just has written her first code and she's a bit nervous as she's getting ready for her first code review.
Alice wants to make her code properly formatted and look nice, but she has no time to read the 328-pages company code style guide, so she decided to format it as a *perfect square*. Alas, code length may be insufficient to form a square, so she decided to leave a *rectangular* gap in the middle. Gaps must be perfectly *centered* and as *close to square* as possible.
### Examples
```
++++++         +++++         +++++         +++++         +++++         +++++
++++++         +++++         +++++         +  ++         ++ ++         +++++
++++++         ++ ++         +   +         +  ++         +   +
++++++         +++++         +++++         +++++         ++ ++         +++++
++++++         +++++         +++++         +++++         +++++         +++++
Perfect         OK         Acceptable   Unacceptable    No way!        Nope.
```
Write a program or a function to help Alice.
Given Alice's code as an input string, output properly formatted code as described below if possible.
If formatting is impossible, output crying emoji `:~(`.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers are scored in bytes with fewer bytes being the aim.
### Constraints
1. Your program or function should take a single string as an input and output one or more lines of text (or return multi-line string or array of strings, if you implement a function).
2. Input string may contain any ASCII characters including whitespaces.
3. All whitespaces in input must be ignored. They shouldn't count for code length and they shouldn't be used in output.
4. Input string contains at least one non-whitespace character.
5. Formatted code must have the same non-whitespace characters in the same order as in input code.
6. Formatted code must be a perfect square, i.e. all lines should have same length, and number of lines should be equal to the lines' length.
7. Formatted code may contain a gap in the middle.
8. Only space characters (ASCII code 32) may be used in the gap.
9. Gap (if present) must be rectangular.
10. Every line of formatted code must contain at least one non-whitespace character, i.e. gap width must be strictly less than square width (gap 5x1 is unacceptable for 5x5 square).
11. Gap should be horizontal, i.e. gap width should be greater than or equal to gap height.
12. Gap must be perfectly centered.
13. Consequently gap width and height parity should be the same as square width parity (for example for 5x5 square gap may be 1x1, 3x1, or 3x3).
14. If possible, output square with no gap at all.
15. In case of multiple solutions, choose one with gap closest to square, i.e. difference between gap width and gap height is minimal (for example: gap 10x10 is more preferable than 8x6, and 8x6 is more preferable than 6x2).
16. If still there's a tie, choose solution with minimal gap area (for example gap 2x2 is more preferable than 4x4).
17. If it is impossible to format code at all, output `:~(`.
18. Newline after last line is optional.
19. **[New]** You may safely assume that any character with code below 33 is a white-space. I hope it will help you for golfing.
### Tests
```
Input           Output      Code length     Comment
+++++++++       +++                   9     Alice is lucky, 
                +++                         her code perfectly fits a square. 
                +++
++++++++        +++                   8     Though code length isn't enough for a square, 
                + +                         a small gap fixes it.
                +++
++++++          :~(                   6     No luck, code cannot be formatted.
Hello,          Hell                 12     Input may contain any ASCII characters, 
World!          o  ,                        but whitespaces in input should be ignored.
                W  o
                rld!
+++++ + +++++   +++++                22     Gap is not required to be a square, 
+++++ + +++++   +++++                       it can be a rectangle.
                +   +
                +++++
                +++++
+++ + +++       ++++++++             28     There exists another solution: 
+++ + +++       +      +                    6x6 square with 4x2 gap, 
+++ + +++       +      +                    but in Alice's opinion square gap 
+++ + +++       +      +                    makes code more readable.
                +      +
                +      +
                +      +
                ++++++++
```
### Tricky tests
```
This must be    Thism                24     7x7 with 5x5 gap looks good,
5x5 with 1x1    ustbe                       but 5x5 with 1x1 gap is better,
gap.            5x 5w                       because gap area is smaller.
                ith1x
                1gap.
+++ +++ +++     :~(                  18     In case you tried 5x5 square
+++ +++ +++                                 with 7x1 gap ;)
```
### Resources
To save space you can find sample code and extra test cases on 
[tio.run](https://tio.run/##nVffc6M2EH7nr1Cd6cQEw8W@y7VNMc996tPN9MHxZBQjG82BRISYJPfQfz3dFb8EyHHniE0E2v12v93VSi7fdCbF5/f3lB3JUaqC6uVBpsy/9whcV6TSipfkJeOaVSU9sMq8N29Llj6iLNmS3SGjih40UwhChicuiBHhRyKkHiYiXhm4pb/3WktHLtJGOGfipDPzGp8fm2cwA4PlyLTv9W5SpclRyYKsX9ekeq6pYo2rZvj4wlMDse40hCSVzGvNpQCfa7BNNdEZI4UsmNBG6olV@vHINej9LQXrVCEaOWuBCa8MMy0lyak6MRgRVDFMABshn6RKmTLaje7S9ipc@zdf4q1F9b6xZMWlNQZf2k@1GPgOHLQRb242M4RSaqDFaU5OtCQV/8F6CXgxQTFPoR19Gw@SiRgtc8Wea65YSoA0vKKkZOrIDhqj0Cs1Kq2VLbm972fwGj1YQR@FaUVu4eOPZQHv@8S1IS9P/ESYkPUps5Pi9ClBl0bQV6Skius3Ihu2VSbrPDUow4RVZxbqqOR@JRtkvB4z7sKeMX7KtKlLe4rlFbugsJm6q9VbQxOTrWSJaxHWmlTVSLApwG@qdhhwloqh4fSlW1N9FD99snz0HPCIV9SVhiSTTCr@QwpN85lgm5kGP7Yw5y47qsBtTkFJUnGqYZFOK25m8mYU6oGg2/zVEKauSsCezqjoatEdQgdTu3LcxhqDBf0ODagG6KEWGwyaVxKm9SFj1VmAkdW2QKdFe948ccVvWkYKoj7urx@qgEf9uoeVi932Ywc@7hQ9u5WVSf9DQPeSm1OT0NDVQI298kpXK9ia9HUF/aUoMeEgU1zEsrMQWgUX98R2633Yjzf7y@79VFQ@6jMBNBqT7@mu09RJYG2oQIcXpawq/pQ3u6A5TngX0ytrXdbo7vX9v8trb54Mg90hg@9MG7Q@CU7fztAFM50n9r6hM3ALPtUzxVVFj3h4oXlO/vSn6D2Obc3znGsrme50bYfFhgGE@Mj7LvQ5O86SB5txj@pjn93M1LQsLa3Wy9DOtFtPOeiA3rrVRW9mOk9SazhqbcnUWqcFznjnV5Y5fYHYOeoDHdvBkeFwbaevOf69cPCcFSX0QzwlitO8xBYLW42KtG1Vw4kVOikXIDwkVKTsFVRvR@cMEKUaF7oy54umbnoBPAQr@YLHXwWbDhvl0h8HwxyYoZILMRNv8@baqHG1iYrDGRPCsuoImjP1ub3NBDfedsZiO7q0KUoTdZhA32M74u7W01qFLrAgC@//d9S2i@IhtMMQ7NXKwgVro98AO5OgvXt7NbkLpscrqD/2QnIuxrGy6DyIgY8ZKKZrJVqR9xKqSy/b30uL9ebzl7uvv/3@x8L3PffU2ZmFv2Ii3YJBMDmV@YvluVw9iH@kytNf5hgBXgT@zH@4Ri@c8s3kg7gwnOt@ww7ZHabuXu@a1YY/tqBKojO25l/gS84TDnZhmIS7JAmSEK843sdwh9E@CaME3sMtigBnFyX7GC4cR0Y2jOLYyIDQ3B1EieNgF@xig52YPwDYIw4qm5gFBgRu8Iym4NMZMU9oJA6iM6lAv5LujoPmi34CgQBZgXc7JLVHOHS61Ys6G2B@RCpsr8iQD4zt9/8A "Alice's First Code Review - Python 3")
**[New]** You may take a look at [the table of accepted solutions for inputs upto 100 characters](https://pastebin.com/9BmzyA3Z). I swapped width and height because it seems to look more intuituve.
Inspired by: [A square of text](https://codegolf.stackexchange.com/questions/88926/a-square-of-text/)
### Changes
* Added 2 tests, fixed bug in sample code.
* Added table of solutions upto 100, added white-space clarification.
  
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 80 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ö╦Çc▀╕╡ëé╓]µiÖ9♪`W|╣▐↑╖D┘↕♫╗╔äƒ■úφ■U`ÿ⌠%é┴☼vAú)☺@Ä±◄¬¶¢(îÉ┼6⌠D~♀└lfæA.I@º╤∟òîü╦(
```
[Run and debug it](https://staxlang.xyz/#p=94cb8063dfb8b58982d65de66999390d60577cb9de18b744d9120ebbc9849ffea3edfe556098f42582c10f7641a32901408ef111aa149b288c90c536f4447e0cc06c6691412e4940a7d11c958c81cb28&i=%2B%2B%2B%2B%2B%2B%2B%2B%2B%0A%0A%2B%2B%2B%2B%2B%2B%2B%2B%0A%0A%2B%2B%2B%2B%2B%2B%0A%0AHello,%0AWorld%21%0A%0A%2B%2B%2B%2B%2B+%2B+%2B%2B%2B%2B%2B%0A%2B%2B%2B%2B%2B+%2B+%2B%2B%2B%2B%2B%0A%0A%2B%2B%2B+%2B+%2B%2B%2B%0A%2B%2B%2B+%2B+%2B%2B%2B%0A%2B%2B%2B+%2B+%2B%2B%2B%0A%2B%2B%2B+%2B+%2B%2B%2B%0A%0AThis+must+be%0A5x5+with+1x1%0Agap.%0A%0A%2B%2B%2B+%2B%2B%2B+%2B%2B%2B%0A%2B%2B%2B+%2B%2B%2B+%2B%2B%2B&a=1&m=1)
How does it work?
* Consider all squares with rectangle cutouts.
* Filter out program shapes that aren't the right size.
* Filter out program shapes that don't have matching parity.
* Filter out program shapes where the cutout is too big for the square.
* If none are found, output failure and quit.
* Find the shape that minimizes "rectangularity" of cutout, then by cutout size.
* Replace each character in the program shape with the corresponding character in the program input.
Unpacked, ungolfed, and commented it looks like this.
```
                input e.g. "big socks"
L$j$            remove whitespace from input e.g. "bigsocks"
cr{~F           copy push each remaining character to input stack in reverse order
%c              get length L of flattened input and copy e.g. 8
^r3:$           create triples [a,b,c] in range 0..n e.g. [[0,0,0], [0,0,1], ... [8,8,8]]
{E*NsJ+n=f      filter triples: require a*a-b*c=L e.g. [[3,1,1], [4,1,8], ...]
{ET>f           filter triples: a>b and a>c e.g. [[3,1,1]]
{{2%m:u_0#+f    filter triples: a%2=b%2=c%2 or b*c=0 e.g. [[3,1,1]]
":~("s|c        if there are no triples, output ":~(" and terminate
{D:s_D:*\oh     sort by [abs(b-c),b*c]; keep the first e.g. [3,1,1]
X               store the chosen triple in the X register
E               explode onto stack e.g. 3, 1, 1
z)]*            using last two values, make a rectangle of zeroes e.g. 3, [[0]]
~               this will be the cutout, push it to the input stack
c'X*]*          make a square of "X" e.g. ["XXX", "XXX", "XXX"]
xEd-h           given the dimensions in x register, calculate the centered cutout coordinates
xEsd-h          e.g. ["XXX", "XXX", "XXX"], 1, 1
,||             embed the cutout grid at the specified coordinates e.g. ["XXX", "X X", "XXX"]
m'X{,]}R        for each line, regex replace "X" with a character from the input stack
```
[Run this one](https://staxlang.xyz/#c=++++++++++++%09input+e.g.+%22big+socks%22%0AL%24j%24++++++++%09remove+whitespace+from+input+e.g.+%22bigsocks%22%0Acr%7B%7EF+++++++%09copy+push+each+remaining+character+to+input+stack+in+reverse+order%0A%25c++++++++++%09get+length+L+of+flattened+input+and+copy+e.g.+8%0A%5Er3%3A%24+++++++%09create+triples+[a,b,c]+in+range+0..n+e.g.+[[0,0,0],+[0,0,1],+...+[8,8,8]]%0A%7BE*NsJ%2Bn%3Df++%09filter+triples%3A+require+a*a-b*c%3DL+e.g.+[[3,1,1],+[4,1,8],+...]%0A%7BET%3Ef+++++++%09filter+triples%3A+a%3Eb+and+a%3Ec+e.g.+[[3,1,1]]%0A%7B%7B2%25m%3Au_0%23%2Bf%09filter+triples%3A+a%252%3Db%252%3Dc%252+or+b*c%3D0+e.g.+[[3,1,1]]%0A%22%3A%7E%28%22s%7Cc++++%09if+there+are+no+triples,+output+%22%3A%7E%28%22+and+terminate%0A%7BD%3As_D%3A*%5Coh+%09sort+by+[abs%28b-c%29,b*c]%3B+keep+the+first+e.g.+[3,1,1]%0AX+++++++++++%09store+the+chosen+triple+in+the+X+register%0AE+++++++++++%09explode+onto+stack+e.g.+3,+1,+1%0Az%29]*++++++++%09using+last+two+values,+make+a+rectangle+of+zeroes+e.g.+3,+[[0]]%0A%7E+++++++++++%09this+will+be+the+cutout,+push+it+to+the+input+stack%0Ac%27X*]*++++++%09make+a+square+of+%22X%22+e.g.+[%22XXX%22,+%22XXX%22,+%22XXX%22]%0AxEd-h+++++++%09given+the+dimensions+in+x+register,+calculate+the+centered+cutout+coordinates%0AxEsd-h++++++%09e.g.+[%22XXX%22,+%22XXX%22,+%22XXX%22],+1,+1%0A,%7C%7C+++++++++%09embed+the+cutout+grid+at+the+specified+coordinates+e.g.+[%22XXX%22,+%22X+X%22,+%22XXX%22]%0Am%27X%7B,]%7DR++++%09for+each+line,+regex+replace+%22X%22+with+a+character+from+the+input+stack&i=big+socks&m=1)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~354~~ 348 bytes
-6 thanks to ceilingcat
```
h,i,j,k,l,m;g,v,w,d;f(char*s){for(j=l=0;i=s[j];d=g=l+=!isspace(s[j++]));for(;i++<l;)if(h=i*i-l)for(j=0;j<i-++j;h>0&h%k<1&k<=m&m<i&m+~k&m-k<g|m==k+g&(d-2*v)*(d-2*w)>h?w=i-m>>1,v=j,g=m-k,d=i:0)k=i-2*j,m=h/k;else g=0,v=w=d=i;if(g-l)for(i=j=1;*s;j+=!i++,k=0,i%=~d)for(putchar(i?v>=j|j>d-v|w>=i|i>d-w?k=1,*s:32:10);k;k*=isspace(*++s));else puts(":~(");}
```
[Try it online!](https://tio.run/##fZLbjpswEIZfhSAt8okupNqbmCG3fYBKvUiiKuU4NiZRzMIqm82rpwaWqr2pufB4/t/DzCdnYZVlj0ctUCihRSOMrEQvBpHLkmT18cIsfS9PF6KggUgi2J06yBwqaDis0NrzMSuIS3J@oFSOTomcJ42kWJIakGHY0LlAJFWCIedK1mkU1E86iQOdgAlMgoHhdx2YUCfVzQBoXgUkD9esp2zaB5rW2wEwNGkaix6UqMC5RQ64iah2wpopYaB@1rJobOFVEDnbAM4gXSfVZxcICmLJrFRj@5wL7Xz4BPd8ks@v3Tg0wW2fgrqpNA/725AC3tCFw1ZDLJjdfF1v4ohKLTWDhQHj3DoC089dGUv8zZ34VH48rtIcsSUzx4lptzvAu8@X5Qv/T/CtaJqT2Lc/TpcmXy2K575x7dt/jrM8nybpf6Ezf6/ReubVdt6vYt@@vL14A3a1F7/F@7Y6nr8s9fjfd/ly@6f/4YaX18TitTiVXvc8B6yT88A@FSXpdtfxLYglNXG14NKHkftwwa4gsbCOPbMrcBxHRr8B "C (gcc) – Try It Online")
[Answer]
# JavaScript (ES6), ~~284 ... 274~~ 270 bytes
*Saved 4 bytes thanks to @Shaggy*
Returns an array of strings.
```
s=>(s=s.replace(/\s/g,''),n=s.length,o=[':~('],W=d=g=(x,w=0,h=p=0)=>4*~-x>n?o:h>w?++w>x-2?g(-~x):g(x,w):g(x,w,h+1,o=n-x*x+w*h|(w^x|h^x)&!!(w|h)|w-h>d|w-h==d&w>W?o:[...Array(x)].map((_,Y,a)=>a.map((_,X)=>2*X>=x-w&2*X<x+w&2*Y>=x-h&2*Y<x+h?' ':s[p++]).join``,d=w-h,W=w)))``
```
[Try it online!](https://tio.run/##lU/LboMwELzzFc4ltrEhDzUXVIN66wdUSqI8Cg0EExGMMK1dCeXXqUmaqpVSKfjg2R3vzKwP0Uckd1VW1k4h4qTds1YyH0km3Sop82iXoNFajlIKIaaFYfOkSGtOBVtB74Tghs5ZzFKGNFVsTDkr2Rgz/8E@OdovAuFxXwWEKF870yBFzkljL@2Gv4FyMjFmhaNtTZTNG6S2uuFbjYeDAVINx41yuB93N2PxUPlzY7pyXfepqqJPpPHGPUYlQq90SSOTHF3bhWmm9sJn2lFDUzwaf4PLjuBdYQgeQAA9uSoJ2WD3ILIiDGnMTJb5lsIYh2G7E4UUeeLmIkV7ZAEAyfVA6yJCcF1ADAg4o2X9L@mruH/@OclzQc0rIF07F1UeD3rGmYEz/rj8YXuZXUS/je5n7g964ZkEx3dZg7cEzPQMqKzmYKInII1Kt@fC5MY65MZCuP0C "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 120 bytes
```
≔Ｅ⮌⪫⪪Ｓ ωιθ≔⁰ηＦ⊕Ｌθ¿⁼Ｌθ×ιι«≔ιη≔ιζ≔ιε»Ｆ⊘ιＦ⊕κＦ∧⁼Ｌθ⁻×ιι×⁻ι⊗⊕κ⁻ι⊗⊕λ∨¬η›⁻ζε⁻κλ«≔ιη≔⊕κζ≔⊕λε»¿η«ＵＯη#ＪεζＦ›η⊗ζＵＯ⁻η⊗ε⁻η⊗ζψＵＭＫＡ⊟θ»:~(
```
[Try it online!](https://tio.run/##dVJRT8IwEH6WX9HMly6si89KlhA1KhEhwhvhYcDBGrp2dB1GjP71ed06YSqXtL279vv69XrLJNZLFYuy7Oc530g6jDP6CnvQOdCB4pJOMsENfZJZYSZGc7mhfkA84uH85uPEcez8m47DXwUkwWitNEHQUkMK0sCKPoPcmITufN8nfE3o/a6IRX5MB2TKU8gpt4x45qNz4Rh5zXgSHtohYPhJQORAqmsfY7HHG5GG/JGxbZJ9ufpHw5DLIqcnShpZ9Qam7lSxEEj0i/QHe@aI8CsLyEjTF2Vogu6DhtiAdtwH@5CGZRuQGnG@Dm0B7aK0b3YV6tiyJxXjaCEUfmSCH3npWdygSLOpouBoqgo18pLjiw5WkQPXQk824ViENiQg75YUO@tWpWmMhR8DbPtC2E4aq8w2hdVX/eAYW8xQ7/qLorCy7DqbRc1snXr00Ng8Qi9iUdSd9eY2jMKIMRY6XGidEJM9FvYqn1XmFnQQGSJfWLK9@AY "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔Ｅ⮌⪫⪪Ｓ ωιθ
```
Strip the spaces from the input, then reverse it and split it into characters, so that we can loop over the characters more easily later.
```
≔⁰η
```
Start with a size of zero, indicating no result found (yet).
```
Ｆ⊕Ｌθ
```
Check all side lengths up to the length of the string. (Throwing a division in would of course make the code faster.)
```
¿⁼Ｌθ×ιι«≔ιη≔ιζ≔ιε»
```
If the result turns out to be a perfect square then save the square size and also set that as the border size.
```
Ｆ⊘ιＦ⊕κ
```
Loop over the possible border heights and widths (the border width is no greater than the border height, making the gap height no greater than the gap width.)
```
Ｆ∧⁼Ｌθ⁻×ιι×⁻ι⊗⊕κ⁻ι⊗⊕λ∨¬η›⁻ζε⁻κλ«≔ιη≔⊕κζ≔⊕λε»
```
If the size of the border is the desired length and we don't have a solution yet or it's not as square as this solution then update the solution with this square and border sizes.
```
¿η«
```
If we have a solution...
```
ＵＯη#
```
Draw a rectangle of an arbitrary character of the given square size.
```
ＪεζＦ›η⊗ζＵＯ⁻η⊗ε⁻η⊗ζψ
```
If the border is small enough to leave a gap then erase the gap. (The drawing command will draw upwards and leftwards for negative values and doesn't like zero values at all.)
```
ＵＭＫＡ⊟θ
```
Replace all (remaining) characters with characters from the input.
```
»:~(
```
Otherwise output `:~(`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~91~~ 85 bytes
```
ÆDżU$<Ạa;ḂEɗʋƇṢƑƇ;€€
ḟ⁶ḟ⁷;©⁶L’²<¥Ðḟ²_ç;,`Wɗ¹?⁸ʋ€$Ẏạ/ÞḢµIH+""Rp"/ḟ@/ŒṬ€ĖP€Sị®Yµ“:~(”¹?
```
[Try it online!](https://tio.run/##y0rNyan8//9wm8vRPaEqNg93LUi0frijyfXk9FPdx9of7lx0bOKxdutHTWuAiOvhjvmPGreBye3Wh1YC2T6PGmYe2mRzaOnhCUDhQ5viDy@31kkIPzn90E77R407TnUDtak83NX3cNdC/cPzHu5YdGirp4e2klJQgZI@UIOD/tFJD3eCzD4yLQBIBj/c3X1oXeShrY8a5ljVaTxqmAs05781kHdoW82hbWWHtgGFrA@3cx2d/HDn4keN@w5tO7TtcDtQZxaU8/@/NgxwcaGzuLg8gN7N1wnPL8pJUYSKKgAhWBKVxwXnEGBxhWRkFivklhaXKCSlcplWmCqUZ5ZkKBhWGHKlJxboQQ3SRtIGwQA "Jelly – Try It Online")
A monadic link that takes the input string as its argument and returns a string either with the formatted output or `:~(`.
[Answer]
# Python 2, ~~287~~ ~~281~~ 279 bytes
```
c=list("".join(input().split()))
l=len(c)
p=[]
for q in range(l*l):x=q%l;y=q/l;s=(l+x*y)**.5;p+=[(abs(x-y)/2,int(s),-x)]*(s%1==0)*(x<s-1>y>=s%2==x%2==y%2or x<1)
if p:d,s,x=min(p);b=(s+x)/2;Y=0;exec"c[b:b]=' '*-x*(b+d<=Y<s-b-d);print''.join(c[:s]);c=c[s:];Y+=1;"*s
else:print':~('
```
[Try it online!](https://tio.run/##JY@9jsIwEIT7PIUVKcra@YFEorFZnuIaFKXAxoBPxhg26JzmXj2XE81MM/pmJs7T7RH6ZTHoHU2Q5@33wwVwIb4n4C1F71bnPPPobQDDs4jDmF0eL/ZkLrDXKVwteOG5TPgsvJrxufGKEHyVxMyFaHcqVjjASROkZuabvnZhAuJ1k/gogIoOccsFpD013WE@IBU9YvqXuejXorTveOYuLMpzTXXC@zowcqURqEorTx1xq2yyJjeDlnrEkpWiSQJ0dd7jccXq5sxVfK29Zfk5aAZJI1cGzUByVMcKO5ULyqwnKz9J@QvlsuRfN0fs/qaJact2acd@3HRjXerY9RTb/A8 "Python 2 – Try It Online")
Uses Python's lexicographic list comparison by using the same values for both choosing a solution and printing it. I'm pretty sure ~~10~~ ~~4~~ 2 or so bytes can still be shaved off.
### Explanation
```
c=list("".join(input().split()))
l=len(c)
p=[]
```
Remove whitespaces by splitting with whitespace and joining with `""`, then convert input to a list for later. Also initialize `l` to length of actual code and `p` to list of valid possibilities.
```
for q in range(l*l):x=q%l;y=q/l;s=(l+x*y)**.5;
```
Loop through all possibilities of gap sizes from `0*0` to `l*l`. Compute the edge length of the square with `l` code chars and `x*y` spaces as `s`.
```
p+=[(abs(x-y)/2,int(s),-x)]*(s%1==0)*(x<s-1>y>=s%2==x%2==y%2or x<1)
```
Check if the following conditions match:
* `s % 1 == 0`, i.e. a perfect square would be formed
* `x < s-1 > y`, i.e. `x` and `y` are at most `s-2` and fit inside the square
* `s % 2 == x % 2 == y % 2`, i.e. both `x` and `y` match the edge's parity and can be centered
* but if `x < 1`, i.e. `x == 0`, ignore all but the perfect square requirement
If the conditions matched, add the following items in a tuple to `p` to find the optimal one:
* `abs(x-y)/2`; first find the minimal difference of `x` and `y` to get the most square gap. This is always even so we divide by 2.
* `int(s)`; next find the minimal side length. Since `s` is an integer and increases as the gap area `x*y`, this sorts by gap area.
* `-x`; next find the maximal width to prefer horizontal gaps. This comes after the area due to how it was developed, but the area is the same for `x*y` and `y*x` so it works.
```
if p:d,s,x=min(p);b=(s+x)/2;Y=0
```
If we found any valid layouts, find the optimal one as described above. Compute the horizontal border `b` and initialize the line number `Y` to 0.
```
exec"c[b:b]=' '*-x*(b+d<=Y<s-b-d);print''.join(c[:s]);c=c[s:];Y+=1;"*s
```
If the line number `Y` is inside the gap (the vertical border is `b+d`, with `d` from the tuple), add the gap width's worth of spaces after the horizontal border in `c`. (The modification of `c` is why we need it to be a list.) Then print a line of the square and remove it from `c`. Repeat `s` times, incrementing the line number.
```
else:print':~('
```
If no layouts were found, fail.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~99~~ 98 bytes
```
#JscQ)=QshKh|oaFtNSf!|%hT1&eT|t{%R2TgeStThT+L@+lJ*Fd2^UJ2
":~("Am/-Qd2tKW=W}~hZrG-QGJj*eKdcJ]H<~>J
```
[Try it online!](https://tio.run/##K6gsyfj/X9mrODlQ0zawOMM7oyY/0a3ELzhNsUY1I8RQLTWkpqRaNcgoJD01uCQkI0Tbx0E7x0vLLcUoLtTLiEvJqk5DyTFXXzfDO8WoxDvcNry2LiOqyF030N0rSyvVOyXZK9bDps7O6/9/pZCMzGKF3NLiEoWkVAXTClOF8sySDAXDCkOF9MQCPSUA "Pyth – Try It Online")
This uses the same algorithm as my Python answer, but many details are significantly changed to be shorter in Pyth.
Pyth shows its age here, since it hasn't been updated in ages and only uses the printable ASCII characters (for code, not data), wasting a lot of space.
Interestingly, if Pyth used the same kind of base-256 packing as Stax, this program could be ⌈98 log256 95⌉ = 81 bytes long, right next to Stax (80 bytes) and Jelly (85 bytes). I think this nicely shows how close golfing languages are even with their drastically different paradigms.
### Explanation (only slightly less unreadable than the code)
`#` wraps everything in a `while True:` that suppresses the message and quits on error.
`JscQ)` `c`hops input (`Q`) at whitespace, `s`ums the parts together and saves the result in `J`.
`^UJ2` makes the list of indices (`U`) of `J` and takes its `2`nd Cartesian power (`^`), resulting in all pairs `[h,w]` with `0<=h<len(J)` and `0<=w<len(J)`.
`+L@+lJ*Fd`: for all (`L`) such pairs `d`, adds (`+`) the square root (`@`…`2`) of (the `l`ength of `J` plus (`+`) the product (`*F`) of the pair `d`) to the left side of the pair, creating a triplet `[side length, gap height, gap width]`.
`f!|%hT1&eT|t{%R2TgeStThT`: `f`ilter for triplets `T` where
* neither of (`!|`):
	+ side length (`hT`) modulo 1 (`%`…`1`) is nonzero
	+ both of (`&`):
		- gap height (`eT`) is nonzero
		- either of (`|`):
			* each number in the triplet (`R`) modulo 2 (`%`…`2`), with duplicates (`{`) and the first unique (`t`) removed, is nonempty
			* the larger (`eS`) of gap height and gap width (`tT`) is `g`reater-or-equal than side length (`hT`)
`S` sorts the triplets lexicographically (by side length, then by gap height). `oaFtN` then `o`rders the triplets by the `a`bsolute difference between gap height and gap width (`tN`).
At this point, if we have no valid solutions, `|` evaluates its second argument, `\n":~("`, which prints and returns `:~(`. `h` takes the optimal solution (or `":"` if none) and it is saved in `K`. Then `h` takes its side length (or `":"` if none), `s` casts it to integer (or fails and quits if none) and it is saved (`=`) in `Q`.
Each of (`m`) `[gap height, gap width]` (`tK`) is then subtracted (`-`) from side length (`Q`) and the result divided by 2 (`/`…`2`). The results are `A`ssigned to `G` and `H`.
Finally, we enter a `W`hile loop. `Z` starts at 0 and each iteration we increment it but use the old value (`~hZ`, think `Z++` in C).
* If (`W`) the old value is in (`{`) the `r`ange `G` to (side length - `G`) (`-QG`), assign (`=`) to `J` the following: `c`hop `J` at position (`]`) `H` and `j`oin the halves with gap width `eK` times (`*`) a space (`d`). If the value was not in the range, just return `J`. If this result is empty, stop the loop.
* Remove (`>`) the first `Q` characters from `J` and assign (`~`) the result to `J`. From the old value of `J`, take (`<`) the first `Q` characters and print them.
Finally, the `#` loop starts again, errors and quits because `cQ)` with `Q` containing a number is invalid.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~95~~ 89 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
… 
    мDg©Ý3ãʒćnsP-®Q}ʒć‹P}ʒÈËyß_~}Dg_i…:~(ëΣ¦DÆÄsP‚}н©¤_iнë¬Ućα¤®Ås<иs;R`X*+šXnª£®θð×ýX}ô»
```
A few bytes here and there can definitely be golfed.
The first three steps of the program are inspired by [*@recursive*'s Stax answer](https://codegolf.stackexchange.com/a/187802/52210), so make sure to upvote him!
[Try it online](https://tio.run/##Ab4AQf9vc2FiaWX//@KApiAKCdC8RGfCqcOdM8OjypLEh25zUC3CrlF9ypLEh@KAuVB9ypLDiMOLecOfX359RGdfaeKApjp@KMOrzqPCpkTDhsOEc1DigJp90L3CqcKkX2nQvcOrwqxVxIfOscKkwq7DhXM80LhzO1JgWCorxaFYbsKqwqPCrs64w7DDl8O9WH3DtMK7//9BIGxvbmcgdGVzdCB0byBzZWUgaWYgaXQgd29ya3MgYXMgaW50ZW5kZWQu) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaCkU6nDpeRfWgLj/X/UsEyBi/PCHpf0QysPzzU@vPjUpCPtecUBuofWBdaC2I8adgYAGYc7DndXHp4fX1frkh6fCdRlVadxePW5xYeWuRxuO9xSHPCoYVbthb2HVh5aEp95Ye/h1YfWhB5pP7fx0JJD6w63Fttc2FFsHZQQoaV9dGFE3qFVhxYfWndux@ENh6cf3htRe3jLod3/a3U0Yw5ts/8fraQNA0o6CkqYbBDLIzUnJ18nJi88vygnRREupwCEIBCTh8KFykO4YDl8TJDqkIzMYoXc0uIShaTUmDzTClOF8sySDAXDCsOYvPTEAj24idrIurXh@h0VcvLz0hVKUoEmlOQrFKemKmSmKWSWKJTnF2UXKyQWK2TmlaTmpaSm6CnFAgA).
**Explanation:**
Step 1: Remove all white-spaces:
```
… 
                   # Push string " \n\t"
    м              # And remove those from the (implicit) input-string
```
Step 2: Create all possible triplets \$[a,b,c]\$, where \$a\$ is the dimension of the resulting \$a×a\$ square, and \$b×c\$ is the size of the gap. We do this by creating all possible triplets using integers in the range \$[0,a]\$. And then we filter these where all of the following is truthy for the triplet:
* \$a^2-b×c=L\$, where \$L\$ is the length of the string
* \$(a\gt b)\text{ and }(a\gt c)\$
* \$(a\pmod2=b\pmod2=c\pmod2)\text{ or }(min(a,b)\neq0)\$
For example: \$L=28\$ will result in the triplets `[[6,2,4],[6,4,2],[8,6,6]]`.
```
Dg                 # Get the length of this string (without popping by duplicating first)
  ©                # Store this length in variable `®` (without popping)
   Ý               # Create a list in the range [0,®]
    3ã             # Create all possible triplets by repeating the cartesian product 3 times
ʒ                  # Filter these triplets by:
 ć                 #  Extract head; pop and push remainder-list and head to the stack
  n                #  Square the head
   sP-             #  Take the product of the remainder, and subtract it from the squared head
      ®Q           #  And check if it's equal to the string length in variable `®`
}ʒ                 # Filter the remaining triplets further by:
  ć‹P              #  Where the first integer is larger than the other two
}ʒ      }          # And filter it a third time by:
  ÈË               #  Where all three are either odd or even
       ~           #  Or
    yß_            #  It does not contain any 0s
```
Step 3: Check if we still have any triplets left. If not, output `":~("`; if we do, determine which one to use by sorting and only leaving the first. We do this by sorting the tuples \$(abs(b-c),b×c)\$.
For example: the triplets `[[6,2,4],[6,4,2],[8,6,6]]` will be sorted to `[[8,6,6],[6,2,4],[6,4,2]]`, after which only `[8,6,6]` remains.
```
Dg_i               # If this completely filtered list is now empty:
    …:~(           #  Push string ":~("
ë                  # Else:
 Σ                 #  Sort the triplets by:
  ¦                #   Remove the first character
   DÆÄ             #   Get the absolute difference between the remaining two integers
   sP‚             #   And pair it with the product of the remaining two integers
      }н           #  After we're done sorting: only leave the first triplet
```
Step 4: Create a list on how we should split the string to insert the spaces. This is done like this:
Given \$[a,b,c]\$, create a list with:
* As first item: \$\frac{a-b}{2}×a + \frac{a-c}{2}\$
* As middle \$b-1\$ items: \${a-c}\$
* As last item: \$a^2\$
For example: triplet `[7,3,5]` will result in the list `[15,2,2,35]`.
```
©                  #  Store this triplet in variable `®` (without popping)
 ¤_i               #  If the last value is 0 (which means the string is a square without gap):
    н              #   Simply keep the first value of the triplet
   ë               #  Else:
    ¬U             #   Store the first value in variable `X` (without popping)
      ć            #   Extract the first value; pop and push remainder-list and head to the stack
       α           #   Get the absolute difference of this head with the other two values
        ¤          #   Push the last value (without popping the pair itself)
         ®Ås<и     #   And repeat it the middle element or `®` minus 1 amount of times
       s           #   Swap to get the difference pair again
        ;          #   Halve both values
         R`        #   Push them reversed to the stack
           X*      #   Multiple the first value by `X`
             +     #   And then add it to the second value
              š    #   Prepend this in front of the repeated list
               Xnª #   And also append the square of `X`
```
Step 5: And finally we split the string based on this list, join it back together with \$c\$ amount of spaces, split it into parts of size \$c\$, and join those together by newlines. For example:
String `"Alongtesttoseeifitworksasintended."` split according to list `[15,2,2,35]` will result in: `["Alongtesttoseei","fi","tw","orksasintended."]`. This is then joined by \$c=5\$ amount of spaces to `"Alongtesttoseei fi tw orksasintended."`. And then split into parts of size \$a=7\$ to this: `["Alongte","sttosee","i f","i t","w o","rksasin","tended."]`. Which is then joined by newlines to output.
```
    £              #   Then split the string into parts based on this list
     ®θð×          #   Push a string consisting of the last value of `®` amount of spaces
         ý         #   Join the list of substrings by this
          X        #   Push variable `X`
   }ô              #  After the if-else: split the string into parts of that size
     »             #  And then join these by newlines
                   # (after which the top of the stack is output implicitly as result)
```
]