text:
Telescopic Parentheses
Consider a non-empty string of correctly balanced parentheses:
(()(()())()((())))(())

We can imagine that each pair of parentheses represents a ring in a collapsed telescopic construction. So let's extend the telescope:
(                )(  )
 ()(    )()(    )  ()
    ()()    (  )
             ()

Another way to look at it is that the parentheses at depth n are moved to line n, while keeping their horizontal position.
Your task is to take such a string of balanced parentheses and produce the extended version.
You may write a program or function, taking input via STDIN (or closest equivalent), command-line argument or function parameter, and producing output via STDOUT (or closest equivalent), return value or function (out) parameter.
You may assume that the input string is valid, i.e. consists only parentheses, which are correctly balanced.
You may print trailing spaces on each line, but not any more leading spaces than necessary. In total the lines must not be longer than twice the length of the input string. You may optionally print a single trailing newline.
Examples
In addition to the above example, here are a few more test cases (input and output are separated by an empty line).
()

()

(((())))

(      )
 (    )
  (  )
   ()

()(())((()))(())()

()(  )(    )(  )()
   ()  (  )  ()
        ()

((()())()(()(())()))

(                  )
 (    )()(        )
  ()()    ()(  )()
             ()

Related Challenges:

Topographic Strings, which asks you to produce what is essentially the complement of the output in this challenge.
Code Explanation Formatter, a broad generalisation of the ideas in this challenge, posted recently by PhiNotPi. (In fact, PhiNotPi's original description of his idea was what inspired this challenge.)

Leaderboards
Huh, this got quite a lot of participation, so 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

function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){$.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(e){answers.push.apply(answers,e.items);if(e.has_more)getAnswers();else process()}})}function shouldHaveHeading(e){var t=false;var n=e.body_markdown.split("\n");try{t|=/^#/.test(e.body_markdown);t|=["-","="].indexOf(n[1][0])>-1;t&=LANGUAGE_REG.test(e.body_markdown)}catch(r){}return t}function shouldHaveScore(e){var t=false;try{t|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(n){}return t}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading);answers.sort(function(e,t){var n=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0],r=+(t.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0];return n-r});var e={};var t=0,c=0,p=-1;answers.forEach(function(n){var r=n.body_markdown.split("\n")[0];var i=$("#answer-template").html();var s=r.match(NUMBER_REG)[0];var o=(r.match(SIZE_REG)||[0])[0];var u=r.match(LANGUAGE_REG)[1];var a=getAuthorName(n);t++;c=p==o?c:t;i=i.replace("{{PLACE}}",c+".").replace("{{NAME}}",a).replace("{{LANGUAGE}}",u).replace("{{SIZE}}",o).replace("{{LINK}}",n.share_link);i=$(i);p=o;$("#answers").append(i);e[u]=e[u]||{lang:u,user:a,size:o,link:n.share_link}});var n=[];for(var r in e)if(e.hasOwnProperty(r))n.push(e[r]);n.sort(function(e,t){if(e.lang>t.lang)return 1;if(e.lang<t.lang)return-1;return 0});for(var i=0;i<n.length;++i){var s=$("#language-template").html();var r=n[i];s=s.replace("{{LANGUAGE}}",r.lang).replace("{{NAME}}",r.user).replace("{{SIZE}}",r.size).replace("{{LINK}}",r.link);s=$(s);$("#languages").append(s)}}var QUESTION_ID=49042;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/;var NUMBER_REG=/\d+/;var LANGUAGE_REG=/^#*\s*([^,]+)/
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

	AuthorLanguageSize

Winners by Language

LanguageUserScore

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

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

Alternative title: De-Lisp-ify a string. :P

Are there any restrictions on the color of the output?

@MatteoItalia That's a funny question, I never considered that. In general I would probably regard the output as the byte stream of your output, not as what's displayed on screen, so a change of colour will probably indicate that you sent some additional bytes that don't really belong there. But for this question, I'm going to say the colour doesn't matter (unless it's something like black on black, obviously), and will take this to meta.

@MartinBüttner: nevermind, I found a cleaner way; let's just say that my previous idea would have shaved a byte leaving all the closed parentheses blinking blue over cyan... :-)

@MatteoItalia oh god, I'm glad that didn't happen. ;)

@MatteoItalia: Post that version! It's worth seeing.

@user2357112: that would be the 30 bytes version, but with the first push/pop restored to the original mov ax,0b8c3h/mov es,ax and the lodsw restored to lodsb. IIRC that was 33 bytes, I discarded that possibility because changing the mov/mov with a push/pop already produced that gain without the blinking; however then I resorted to some similar trick to shave some other bytes, so we are back to ugly colors (but no blinking :-( ).

If I had this idea on my Math exams, it would be so cool, for not making mistakes...

CJam, 17 16 15 bytes
0000000: 72 3a 69 22 28 0b 20 9b 41 29 22 53 2f 66 3d     r:i"(. .A)"S/f=

The above is a reversible xxd dump, since the source code contains the unprintable characters VT (0x0b) and CSI (0x9b).
Like this answer, it uses ANSI escape sequences, but it also uses vertical tabs and it prints the control characters directly to avoid using printf.
This requires a supporting video text terminal, which includes most non-Windows terminal emulators.
Test run
We have to set the shell variable LANG and the terminal emulator's encoding to ISO 8859-1. The former is achieved by executing
$ LANGsave="$LANG"
$ LANG=en_US

Also, before executing the actual code, we'll disable the prompt and clear the screen.
$ PS1save="$PS1"
$ unset PS1
$ clear

This makes sure the output is shown properly.
echo -n '()(())((()))(())()' | cjam <(base64 -d <<< cjppIigLIJtBKSJTL2Y9)
()(  )(    )(  )()
   ()  (  )  ()
        ()

To restore LANG and the prompt, execute this:
$ LANG="$LANGsave"
$ PS1="$PS1save"

How it works
We insert a vertical tab after each ( to move the cursor down and the byte sequence 9b 41 ("\x9bA") before each ) to move the cursor up.
r         e# Read a whitespace-separated token from STDIN.
:i        e# Replace each character by its code point.
          e#   '(' -> 40, ')' -> 41
"(. .A)"  e# Push the string "(\v \x9bA)".
S/        e# Split at spaces into ["(\v" "\x9bA)"].
f=        e# Select the corresponding chunks.
          e# Since arrays wrap around in CJam, ["(\v" "\x9bA)"]40= and
          e# ["(\v" "\x9bA)"]41= select the first and second chunk, respectively.

x86 machine code, 39 34 33 30 29 bytes
00000000  68 c3 b8 07 31 ff be 82  00 b3 a0 ad 4e 3c 28 7c  |h...1.......N<(||
00000010  f0 77 05 ab 01 df eb f3  29 df ab eb ee           |.w......)....|
0000001d

x86 assembly for DOS, with some tricks:
    org 100h

section .text

start:
    ; point the segment ES to video memory
    ; (c3 is chosen so that it doubles as a "ret")
    push 0b8c3h
    pop es
    ; di: output pointer to video memory
    xor di,di
    ; si: input pointer from the command line
    mov si,82h
    ; one row=160 bytes (assume bh=0, as should be)
    mov bl,160
lop:
    ; read & increment si (assume direction flag clean)
    ; we read a whole word, so that later we have something nonzero to
    ; put into character attributes
    lodsw
    ; we read 2 bytes, go back 1
    dec si
    ; check what we read
    cmp al,'('
    ; less than `(`: we got the final `\n` - quit
    ; (we jump mid-instruction to get a c3 i.e. a ret)
    jl start+1
    ; more than `(`: assume we got a `)`
    ja closed
    ; write a whole word (char+attrs), so we end
    ; one position on the right
    stosw
    ; move down
    add di,bx
    ; rinse & repeat
    jmp lop
closed:
    ; move up
    sub di,bx
    ; as above
    stosw
    jmp lop

Limitations:

it always prints starting at the bottom of the screen, without erasing first; a cls before running is almost mandatory;
the colors are ugly; that's the consequence of recycling the next character as color attributes to save two bytes here and there;
the code assumes bh=0 and the direction flag clear on start, both undocumented; OTOH, bx is explicitly set to zero in all DOS variants I saw (DosBox, MS-DOS 2, FreeDOS), and everywhere I tested the flags were already OK.

Just verified this. Yes, it works. Are you sure you need to do cld?

@FUZxxl: on DosBox it works fine even without it, but looking at its sources it says that the flags are preserved from whatever happened in DOS and in TRSs before, so probably it would be required to play it safe. Anyhow, that would be just one byte, the real payoff would be to kill at least one of those big (=4 byte each) add/sub.

Hm... no idea, really.

Can you change lop to loop?

@mbomb007: maybe? I'm not sure if nasm disambiguates between loop as a label and loop the assembly instruction, so I just write lop as everybody else does.

That's what I figured, but I wasn't sure. I suppose it might be possible for the loop instruction's opcode to be interpreted as a literal address to jump to?

@mbomb007: I don't think that any assembler ever did that, the source of confusion are labels, since colons are usually optional; see here for a more detailed discussion of this exact issue.

J, 32 28 bytes
This was a fun one.
0|:')(('&(i.-<:@+/\@i:){."0]

Explanation
This is how this solution works, including an explanation of how it has been golfed.
   NB. Let a be a test case
   a =. '((()())()(()(())()))'

   NB. level alterations
   _1 + ').(' i. a
1 1 1 _1 1 _1 _1 1 _1 1 1 _1 1 1 _1 _1 1 _1 _1 _1

   NB. absolute levels
   +/\ _1 + ').(' i. a
1 2 3 2 3 2 1 2 1 2 3 2 3 4 3 2 3 2 1 0

   NB. adjusted levels
   (+/\ _1 + ').(' i. a) - ')(' i. a
0 1 2 2 2 2 1 1 1 1 2 2 2 3 3 2 2 2 1 0

   NB. take level from end of each item of a and transpose
   |: a {."0~ _1 - (+/\ _1 + ').(' i. a) - ')(' i. a
(                  )
 (    )()(        )
  ()()    ()(  )()
             ()

   NB. code as a tacit verb
   [: |: ] {."0~ _1 - ([: +/\ _1 + ').(' i. ]) - ')(' i. ]

   NB. subtractions pulled into the prefix insert
   [: |: ] {."0~ (')(' i. ]) - [: <:@+/\ ').(' i. ]

   NB. i: instead of i. so we can use the same string constant
   [: |: ] {."0~ (')((' i. ]) - [: <:@+/\ ')((' i: ]

   NB. get rid of the caps
   0 |: ] {."0~ (')((' i. ]) - ')((' <:@+/\@i: ]

   NB. join the two usages of ')((' into a single dyadic phrase
   0 |: ] {."0~ ')((' (i. - <:@+/\@i:) ]

   NB. bond ')((' and flip arguments to {."0
   0 |: ')(('&(i. - <:@+/\@i:) {."0 ]

Very nice! The solution is full of great parts!

(I usually add an example invocation of the function so non-experienced users could try it out too.)

This solution makes my head hurt :')

@QPaysTaxes I take this as a compliment.

@FUZxxl It is. It's also a pun based on a sequence of characters that appears in your answer.

C, 150 bytes
t;f(char*c){char l=strlen(c)+1,o[l*l],*A=o,m=0;for(t=1;t<l*l;t++)o[t-1]=t%l?32:10;for(t=-1;*c;c++)A++[l*(*c-41?++t>m?m=t:t:t--)]=*c;A[m*l]=0;puts(o);}

This was crazy fun to golf. I'm still not convinced I'm done with it.
We define a single function, f, that takes the string as input and outputs to stdout.
Let's go through the code, line by line:
/* t will represent the current depth of a parentheses. It must be an int. */
t;
f(char*c){
    //Our variables:
    char l=strlen(c)+1,    //The length of each row of output, including newlines
         o[l*l],           //The output string. It's way larger than it needs to be.
         *A=o,             //We need another pointer to keep track of things.
         m=0;              //The maximum depth recorded thus far.

    for(t=1;t<l*l;t++)     //For each character in our output...
        o[t-1]=t%l?32:10;  //If it's at the end of a line, make it '\n'. Else, ' '.
    for(t=-1;*c;c++)       //While we have an input string...
        //Perhaps a personal record for ugliest warning-less line...
        A++[l*(*c-41?++t>m?m=t:t:t--)]=*c;
    /*
        A breakdown:
        A++        --> Go to the next *column* of output, after writing.
                   --> There will only ever be one parentheses per output column.
        [l*(...)]  --> A[l*X] is the character in the current column at depth X.
        (*c-41?    --> If the character is a '('...
        ++t>m?     --> Increment t *before* we write it. If this is a new highest depth
        m=t:       --> Set m to t, and set the whole expression to t.
        t:         --> If it's not a new highest depth, don't set m.
        t--)       --> If the character was a ')', decrement t *after* we write it.
        =*c        --> Write our output character to whatever the input read.
    */

    A[m*l]=0; //The last character of the maximum-depth line should be null terminated.
    puts(o);  //Output!
}

I'll answer any questions you may have!
Try a test program online!

I want to remember that "char l=strlen(c)+1, o[l*l]" isn't valid because you can't define a variable sized array like that, but it's been 15 years since I tried anything of that sort in C.

@Sparr My compiler doesn't even throw a warning. I believe this was "officially" standard in C99. I will try to find a reference for this.

@Sparr Here is a reference.

Thanks. It does seem things changed around 15 (give or take a couple) years ago in this regard :)

for(t=0;++t<l*l;) or for(t;++t<l*l)

This for(t=l*l;--t;) should always work (t is local and needs to be initialized).

@f.ardelian for(t=l*l;--t;) fails because it tries to access a negative index of o. It should be easily modifiable, though. I'll look at this soon.

@BrainSteel Are you sure the loop executes with a negative index? --t decrements and then checks for 0.

Wouldn't making m a global int save some bytes?

@CoolGuy It would, but on subsequent calls of f, m would not reset to 0. This counts as "breaking your environment," outlawed here.

Retina + Bash, 27 bytes (14 + 10 + 3 = 27)
This makes use of ANSI Escapes:
\(
(\e[B
\)
\e[A)

Equivalent to sed -e "s/(/(\\\e[B/g;s/)/\\\e[A)/g".
The \e[B escape code means move cursor down one row, and the \e[A means move cursor up one row, so this solution simply inserts those codes after and before the start and end of each nested pair of parentheses. Input is passed through STDIN.
You'll have to call it as printf $(Retina ...) to see the output correctly.
Output
(((())))
(\e[B(\e[B(\e[B(\e[B\e[A)\e[A)\e[A)\e[A)
^C
amans:~ a$ printf "(\e[B(\e[B(\e[B(\e[B\e[A)\e[A)\e[A)\e[A)"
(      )amans:~ a$
 (    )
  (  )
   ()

((()())()(()(())()))
(\e[B(\e[B(\e[B\e[A)(\e[B\e[A)\e[A)(\e[B\e[A)(\e[B(\e[B\e[A)(\e[B(\e[B\e[A)\e[A)(\e[B\e[A)\e[A)\e[A)
^C
amans:~ a$ printf "(\e[B(\e[B(\e[B\e[A)(\e[B\e[A)\e[A)(\e[B\e[A)(\e[B(\e[B\e[A)(\e[B(\e[B\e[A)\e[A)(\e[B\e[A)\e[A)\e[A)"
(                  )amans:~ a$
 (    )()(        )
  ()()    ()(  )()
             ()

Well, not bad! If you could point to a specific terminal that doesn't need printf that would be great. Otherwise, I think it would only be fair to add | printf to the byte count.

@MartinBüttner It should be printf $() or printf $(Retina    ).

What's that Retina thingy?

I can't find one which doesn't, so ill add printf $() to the count :)

@FUZxxl It's my own regex-based programming language. See GitHub.

Why \e plus printf? You can simply put the control characters in the replacement pattern.

TI-BASIC, 69 60 56 55 bytes
This is for the TI-83+/84+ family of calculators, although it was written on an 84+ C Silver Edition.
The program shows up as larger on-calc due to VAT+size info being included. Also, there are more than 56 characters here; the reason it's 56 bytes is because all commands that are more than one character are compressed down to tokens that are either one or two bytes in size.
Input Str1
1→B
For(A,1,length(Str1
sub(Str1,A,1→Str2
Ans="(
Output(B+Ans,A,Str2
B-1+2Ans→B
End

Shaved off another byte thanks to thomas-kwa! (also from him was the jump from 60 to 56.)

Ahhh, my first programming language. Thanks for the nostalgia, haha.

Still programing TI for highschool math class, very useful to have formulas built in that will calculate for you on tests and assignments.

If you shift things around you can use the cos(piAns trick to save another byte.

Python 2, 115 bytes
def f(L,n=0,O=()):
 for c in L:n-=c>"(";O+=" "*n+c,;n+=c<")"
 for r in map(None,*O):print"".join(c or" "for c in r)

Call like f("((()())()(()(())()))"), and output is to STDOUT.
Explanation
We start with n = 0. For each char in the input line:

If the char is (, we prepend n spaces then increment n
If the char is ), we decrement n then prepend n spaces

The result is then zipped and printed. Note that Python's zip zips to match the length of the shortest element, e.g.
>>> zip([1, 2], [3, 4], [5, 6, 7])
[(1, 3, 5), (2, 4, 6)]

Usually one would use itertools.zip_longest (izip_longest) if they wanted zip to pad to the length of the longest element.
>>> import itertools
>>> list(itertools.izip_longest([1, 2], [3, 4], [5, 6, 7]))
[(1, 3, 5), (2, 4, 6), (None, None, 7)]

But in Python 2, this behaviour can be simulated by mapping None:
>>> map(None, [1, 2], [3, 4], [5, 6, 7])
[(1, 3, 5), (2, 4, 6), (None, None, 7)]

Python 3, 115 bytes
L,d,*O=input(),0
for i,c in enumerate(L):b=c>"(";O+="",;O[d-b]=O[d-b].ljust(i)+c;d-=b*2-1
for l in O:l and print(l)

No zipping, just padding appropriately with ljust. This one seems to have some golfing potential.

C, 58 53 52 51 49 bytes
Makes use of ANSI escape sequences to move the cursor position.
f(char*s){while(*s)printf(*s++&1?"\e[A)":"(\v");}

If not using gcc or another compiler that supports \e then it can be replaced with \x1B for a total of 2 extra bytes. \e[A moves the cursor up one row and \e[B moves the cursor down one row. It's not necessary to use \e[B to move down one row as it's two bytes shorter to use the ASCII vertical tab character 0xB or \v.
The input string is assumed, from the question, to consist of only (balanced) parentheses, so checking the parity of the character, with &1, is enough to distinguish between ( and ).

R, 151 127 characters
S=strsplit(scan(,""),"")[[1]];C=cumsum;D=c(C(S=="("),0)-c(0,C(S==")"));for(j in 1:max(D)){X=S;X[D!=j]=' ';cat(X,sep='',fill=T)}

With indents and newlines:
S=strsplit(scan(,""),"")[[1]]
C=cumsum
D=c(C(S=="("),0)-c(0,C(S==")"))
for(j in 1:max(D)){
    X=S
    X[D!=j]=' '
    cat(X,sep='',fill=T)
    }

Usage:
> S=strsplit(scan(,""),"")[[1]];C=cumsum;D=c(C(S=="("),0)-c(0,C(S==")"));for(j in 1:max(D)){X=S;X[D!=j]=' ';cat(X,sep='',fill=T)}
1: ()(())((()))(())()
2:
Read 1 item
()(  )(    )(  )()
   ()  (  )  ()
        ()
> S=strsplit(scan(,""),"")[[1]];C=cumsum;D=c(C(S=="("),0)-c(0,C(S==")"));for(j in 1:max(D)){X=S;X[D!=j]=' ';cat(X,sep='',fill=T)}
1: ((()())()(()(())()))
2:
Read 1 item
(                  )
 (    )()(        )
  ()()    ()(  )()
             ()

It reads the string as stdin, splits it as a vector of single characters, computes the cumulative sum of ( and ), substracts the former with the latter (with a lag) thus computing the "level" of each parentheses. It then prints to stdout, for each level, either the corresponding parentheses or a space.
Thanks to @MickyT for helping me shortening it considerably!

+1 Nice and elegant solution.  You can save 6 by replacing for(i in n)cat(ifelse(D[i]-j," ",S[i]));cat("\n") with X=S;X[which(D!=j)]=' ';cat(X,sep='',fill=T).  Then n isn't really required, but you would need change the cumsum part a bit. D=c(C(S=="("),0)-c(0,C(S==")")); bringing it down to 135.

@MickyT wow thanks! didn't thought of that. which is not really necessary here though (D!=j being already a vector of booleans allowing indexing). I didn't know argument fill for cat, that's a nifty trick! Thanks for making me shorten it by an astounding 24 characters!!

Pip, 53 bytes
Pip is a code-golf language of my invention. The first version was published on Saturday, so I can officially take it for a spin! The solution below isn't terribly competitive as golfing languages go, but that's partly because I haven't implemented things like zip and max yet.
z:{aEQ'(?++v--v+1}MaW(o:{z@++v=i?as}Ma)RMs{Pov:-1++i}

Expects the string of parentheses as a command-line argument.
"Ungolfed" version:
z:{
   a EQ '( ?
    ++v
    --v+1
  } M a
W (o:{
      z @ ++v = i ?
       a
       s
     } M a
  ) RM s
{
 P o
 v:-1
 ++i
}

Explanation:
Unlike most golfing languages, Pip is imperative with infix operators, so the syntax is somewhat closer to C and its derivatives. It also borrows ideas from functional and array-based programming. See the repository for further documentation.
The program first generates a list of depths (storing it in z) by mapping a function to the input string a. The global variable v tracks the current level. (Variables a-g in Pip are function-local variables, but h-z are global. v is handy because it's preinitialized to -1.)
Next, we use a While loop to generate and print each line, until the line generated would consist of all spaces. v is now used for columns, and i for rows. The {z@++v=i?as} function, repeatedly mapped to the original input string, tests whether the current line i matches the line the current parenthesis is supposed to be on (as stored in the z list). If so, use the parenthesis (a); if not, use s (preinitialized to space). The end result is that on each iteration, o gets assigned a list of characters equivalent to the next line of the output.
To test whether we should continue looping, we check if o with all the spaces RM'd is empty. If not, print it (which by default concatenates everything together as in CJam), reset the column number to -1, and increment the row number.
(Fun fact: I had a 51-byte solution at first... which didn't work because it turned up a bug in the interpreter.)

Pyth, 31 bytes
VzJs.e?YqN-/<zk\(/<zhk\)dzI-JdJ

Try it online.
-/<zk\(/<zhk\): Finds the appropriate level for the current character position.
?YqN-/<zk\(/<zhk\)d: A space if the appropriate level is not the current level, current character otherwise.
Js.e?YqN-/<zk\(/<zhk\)dz: Generate the string, save it to J.
I-JdJ: If J is not all spaces, print it out.
Vz: Loop z times.

GNU Bash + coreutils + indent, 135
eval paste "`tr '()' {}|indent -nut -i1 -nbap|sed 's/.*/<(fold -1<<<"&")/'|tr '
' \ `"|expand -t2|sed 'y/{}/()/;s/\(.\) /\1/g;s/ \+$//'

Input/output via STDIN/STDOUT:
$ ./telescopic.sh <<< "(()(()())()((())))(())"
(                )(  )
 ()(    )()(    )  ()
    ()()    (  )
             ()
$

indent does most of the heavy lifting, but needs to work with braces instead of parens.  The rest is modification of this answer to transpose the output of indent.

Python 2, 92
def f(s,i=0,z=''):
 for x in s:b=x>'(';z+=[' ',x][i==b];i-=2*b-1
 if'('in z:print z;f(s,i-1)

Prints line by line. For a given line number i (actually, its negation), goes through the input string s, and makes a new string z that only contains the characters of s at depth i. This is done by incrementing or decrementing i to track the current depth, and adding the current characters when i is 0 adjusted for paren type, and otherwise adding a space.
Then, prints and recurses to the next i unless the current line was all spaces. Note that since the parens are balanced, the i after a loop is the same as at the start.
Python 3 would be same except for a character for print(z).

Java, 232 226 224 222 bytes
Golfed version:
int i,j,k,l,m,a[];void f(String s){a=new int[s.length()];j=a.length;for(k=0;k<j;){a[k]=s.charAt(k++)<41?i++:--i;m=m<i?i:m;}for(k=0;k<m;k++)for(l=0;l<j;)System.out.print(k==a[l++]?i++%2<1?'(':l==j?")\n":')':l==j?'\n':' ');}

Long version:
int i, j, k, l, m, a[];
void f(String s) {
    a = new int[s.length()];
    j = a.length;
    for (k = 0; k < j;) {
        a[k] = s.charAt(k++) < 41 ? i++ : --i;
        m = m < i ? i : m;
    }
    for (k = 0; k < m; k++)
        for (l = 0; l < j;)
            System.out.print(k == a[l++] ? (i++ % 2 < 1 ? '(' : (l == j ? ")\n" : ')')) : (l == j ? '\n':' '));
}

The input string is analyzed first, looking for "(" and ")" to add/subtract a counter and store its value determining how far down the parentheses should go in an array while also keeping track of how deep the deepest one goes. Then the array is analyzed; the parentheses with lesser values are printed first, and will continue printing line by line until the maximum is reached.
I'll probably find ways to golf this further later.

Javascript/ES6, 97 chars
f=s=>{for(n in s){m=o=d='';for(c of s)o+=n==(c<')'?d++:--d)?c:' ',m=m<d?d:m;n<m&&console.log(o)}}

Usage
f("(()(()())()((())))(())")

Explanation
fn=str=>{                          // accepts string of parenthesis
  for(line in str){                // repeat process n times where n = str.length
    max=output=depth='';           // max: max depth, output: what to print, depth: current depth
    for(char of str)               // iterate over chars of str
      output+=
        line==(char<')'?depth++:--depth)? // update depth, if line is equal to current depth
        char:' ',                  // append either '(', ')', or ' '
        max=max<depth?depth:max;   // update max depth
    line<max&&console.log(output)  // print if current line is less than max depth
  }
}

Instead of n<m?console.log(o):0, you can use n<m&&console.log(o) which saves 1 byte.

cheating :(  Retina + TeX, N bytes cheating :(
This only works if you render(?) the output using MathJax or some other TeX, which is currently disabled for this SE :(
\(
({
\)
})
\{\(
_{(

Each line should be in a different file, but you can test it by using Retina -e "\(" -e "({" -e "\)" -e "})" -e "\{\(" -e "_{(" (or the equivalent sed command sed -e "s/(/({/g;s/)/})/g;s/{(/_{(/g"). Input is passed through STDIN.
This works by enclosing the contents of each pair of parentheses in braces, and then subscripting all the items inside them.
Output
(((())))
(_{(_{(_{({})})})})

()(())((()))(())()
({})(_{({})})(_{(_{({})})})(_{({})})({})

((()())()(()(())()))
(_{(_{({})({})})({})(_{({})(_{({})})({})})})

I'm flattered that you've used Retina, and this is nice thinking-outside-the-box but that's not quite what the output is supposed to look like. ;) In particular this violates the alternative formulation "Another way to look at it is that the parentheses at depth n are moved to line n, while keeping their horizontal position." I'd be very impressed by a pure, rule-compliant Retina solution though and might hand out a bounty for it. ;)

In total the lines must not be longer than twice the length of the input string.
Changing line 2 to (\,{ and line 4 to }\,) means that the output fits this (although the vertical depth is still wrong : ( )

Well, I managed to make rule-compliant solution : )

Nice job. I guess that means you can delete the cheaty answer now. ;)

CJam, 43 41 36 bytes
Not too golfed (I think), but here goes my first attempt:
l:L,{)L<)_')=@~zS*\+}%_$0=,f{Se]}zN*

How it works
I am using the very handy fact that ) and ( in CJam mean increment and decrement respectively. Thus, I simply evaluate the brackets to get the depth.
l:L,{)L<)_')=@~zS*\+}%_$0=,f{Se]}zN*
l:L,{                    }%                "Store input line in L and iterate over [0,L)";
     )L<                                   "substr(L, 0, iterator + 1)";
        )                                  "Slice off the last character to stack";
         _')=                              "Put 0 on stack if the sliced character is (,
                                            else 1 if sliced character is )";
             @~                            "bring forth the remaining
                                            brackets after slicing and evaluate them";
               zS*                         "Stack has negative depth number, take absolute
                                            value and get that many spaces";
                  \+                       "Prepend to the sliced character";
                      _$0=,                "Get the maximum depth of brackets";
                           f{Se]}          "Pad enough spaces after each string to match
                                            the length of each part";
                                 zN*       "Transpose and join with new lines";

Try it online here

Octave, 85 chars
function r=p(s)i=j=0;for b=s k=b==40;k&&++j;t(j,++i)=9-k;k||--j;r=char(t+32);end;end

It's an optimization of the naïve approach, which is actually pretty natural for Matlab and Octave:
function r=p(s)
i=j=1;
for b=s
 if b=='(' t(++j,i++)='(' else t(j--,i++)=')' end; end; t(~t)=' '; r=char(t);
end;

The table t  may even not yet exist, and we may assign to any element right away, and it reshapes to the smallest dimension that is required for this element to exist which is quite convenient.

Perl, 91 89 88 84 80 79 bytes
$t=<>;{$_=$t;s/\((?{$l++})|.(?{--$l})/$^R==$c?$&:$"/ge;print,++$c,redo if/\S/}

$t is the input string.
$c is the depth we want to print on the current line.
$l is the depth we are at after encountering a paren.
$l is updated in regex embedded code blocks.
$^R is the result of the most recent code block.

Haskell, 154 bytes
f h('(':s)=h:f(h+1)s;f h(')':s)=(h-1):f(h-1)s;f _ _=[]
main=interact$ \s->unlines[[if i==h then c else ' '|(c,i)<-zip s l]|let l=f 0 s,h<-[0..maximum l]]

same idea as the other Haskell solution, but somewhat shorter. - Usage:
echo  '(((())())(()))' | runghc Golf.hs

Japt, 13 bytes
y_ùZ<')?°T:T´

Try it

Explanation
y_                :Transpose, pass each column Z through a function and transpose back
   Z<')           :  Is Z less than ")", i.e., is Z equal to "("?
       ?          :  If so
        °T        :   Prefix increment variable T (initially 0)
          :       :  Else
           T´     :   Postfix decrement T
  ù               :  Left pad Z with spaces to length T

Brain-Flak, 338 bytes
([]){(({})[()]<([{}][])([][()]){({}[()]<(({}<(({})(())){({}[()]<([{}]())>)}>{})<({}{})((){[()](<{}<>((((()()()()){}){}){})<>>)}{}){{}(({})<>)(<>)}{}(({})(())){({}[()]<([{}])>)}{}>{}<({}<(([])<{{}({}<>)<>([])}{}<>>)<>>)<>{({}[()]<({}<>)<>>)}{}<>>)>)}{}{}<>((()()()()()){})<>>)}{}{{}}<>{{}{}(({})[((((()()()){}())){}{}){}]())}{}{({}<>)<>}<>

Try it online!
Idea
The idea for this program is that we make a number of passes over the string.  Each time we make a pass we keep track of a counter, we decrement the counter if we encounter a ( and increment it if we encounter a ).  If ( brings it to -1 we copy it to the offstack and if ) brings it to zero we copy it to the offstack.  Otherwise we just copy a space.  We do this as many times as the length of the string starting the counter at 0 the first time and decreasing it each loop.  This way we catch the different layers in order.  When we are done we just trim characters until we reach a ).

05AB1E, 14 11 bytes
2IDÇÉü+>4αΛ

Try it online.
Explanation:
2        # Push 2
I        # Push the input-string
D        # Create a copy of the input-string,
 Ç       # and convert it to a list of codepoint integers: ")"→41; "("→40
  É      # Check for each if it's odd: ")"→1; "("→0
   ü     # For each overlapping pair:
    +    #  Add them together: "(("→0; "()"→1; ")("→1; "))"→2
     >   # Increase each by 1: "(("→1; "()"→2; ")("→2; "))"→3
      4α # Take the absolute difference with 4: "(("→3; "()"→2; ")("→2; "))"→1
Λ        # Use the Canvas builtin with the given three arguments:
         #  - Directions: the list of 123 we created, for ↗→↘ respectively
         #  - What to draw: the third remaining copy of the input-string
         #  - Line-lengths per step: the 2

Here a step-by-step explanation of the output for input (()(()())()((())))(()):
Preparation step: the overlapping pairs are ["((","()",")(","((","()",")(","()","))",")(","()",")(","((","((","()","))","))","))",")(","((","()","))"], which are mapped with DÇÉü+>4α to [3,2,2,3,2,2,2,1,2,2,2,3,3,2,1,1,1,2,3,2,1], which indicate the directions [↘,→,→,↘,→,→,→,↗,→,→,→,↘,↘,→,↗,↗,↗,→,↘,→,↗]:
7   0   1
  ↖ ↑ ↗
6 ← X → 2
  ↙ ↓ ↘
5   4   3

When we use the Canvas builtin, it then draws like this:
Step 1: draw 2 characters ((() in direction 3 (↘):
(
 (

Step 2: draw 2-1 characters ()) in direction 2 (→):
(
 ()

Step 3: draw 2-1 characters (() in direction 2 (→):
(
 ()(

Step 4: draw 2-1 characters (() in direction 3 (↘):
(
 ()(
    (

Etc.
For an in-depth explanation of the Canvas builtin I can refer to this 05AB1E tip of mine.

Pip -l, 23 22 21 bytes
ZJ:sX{%Aa?DiUi-1}._Ma

Attempt This Online! Or, here's a 25-byte equivalent in Pip Classic: Try it online!
Reminiscence
Pip, old chap, how far we've come.
This clunky 53-byter was my first Pip answer on this site, over six years ago. I'd like to leave that answer untouched as a historical artifact, so I'm posting my modern Pip solution here separately. It's pretty clear that the two are different languages anyway. The old solution doesn't even work in modern Pip (though it still does on the TIO version).
Explanation
ZJ:sX{%Aa?DiUi-1}._Ma
                      ; s is space; i is 0; a is command-line arg (implicit)
                   Ma ; Map this function to each character in the argument:
     { Aa       }     ;   The ASCII code of the character
      %               ;   Mod 2
         ?            ;   Is that truthy (1, close paren) or falsey (0, open paren)?
          Di          ;    If truthy, decrement i and return it
            Ui        ;    If falsey, increment i
              -1      ;    and return i-1 (i.e. the previous value of i)
   sX                 ;   Make a string of that many spaces
                 ._   ;   Concatenate the parenthesis to it
ZJ:                   ; Zip the list of strings to transpose it, padding to
                      ; a rectangle using spaces
                      ; Autoprint (implicit), each sublist on its own line (-l flag)

Ruby, 119 115 114
->s{r=[""]*s.size
d=0
s.chars.map{|l|r.map!{|s|s+" "}
b=l>"("?1:0
d-=b
r[d][-1]=l
d+=1-b}.max.times{|i|puts r[i]}}

Explanation:
->s{r=[""]*s.size  # Take an array of strings big enough
d=0                # This will contain the current depth
s.chars.map{|l|r.map!{|s|s+" "}  # Add a new space to every array
b=l>"("?1:0       # Inc/Dec value of the depth
d-=b               # Decrement depth if we are at a closing paren
r[d][-1]=l         # Set the corresponding space to the actual open/close paren
d+=1-b             # Increment the depth if we are at a opening paren
}.max.times{|i|puts r[i]}}  # Print only the lines up to the max depth

J, 46
Not as great as the other 'golfing languages', but in my defence: J is terrible with strings.
[:|:(((,~(' '#~]))"0)(0,2%~[:+/\2+/\1-'(('i.]))~

Takes the string as input for a function. There's also probably a better way to do it in J.
Usage:
   f=:[:|:(((,~(' '#~]))"0)(0,2%~[:+/\2+/\1-'(('i.]))~
   f '(()(()())()((())))(())'
(                )(  )
 ()(    )()(    )  ()
    ()()    (  )
             ()

See my answer for another way of doing this in J.

Personally, I think that J is perfectly well-suited for strings. You just need to think with arrays.

Java, 233 214 bytes
void f(String s){int p,x,d,l=s.length();char c,m[]=new char[l*l];java.util.Arrays.fill(m,' ');p=x=0;while(x<l){d=(c=s.charAt(x))==40?p++:--p;m[d*l+x++]=c;}for(x=0;x<l*l;x++)System.out.print((x%l==0?"\n":"")+m[x]);}

Indented:
void f(String s){
    int p, x, d, l = s.length();
    char c, m[] = new char[l * l];
    java.util.Arrays.fill(m, ' ');
    p = x = 0;
    while (x < l){
        d = (c = s.charAt(x)) == 40
                ? p++
                : --p;
        m[d * l + x++] = c;
    }
    for (x = 0; x < l * l; x++)
        System.out.print((x % l == 0 ? "\n" : "") + m[x]);
}

I guess the final loop could be shortened, but I'll leave it as an exercise to the reader. ;-)

Old, 233 bytes answer:
void f(String s){int y=s.length(),x=0;char[][]m=new char[y][y];for(char[]q:m)java.util.Arrays.fill(q,' ');y=0;for(char c:s.toCharArray())if(c=='(')m[y++][x++]=c;else m[--y][x++]=c;for(char[]q:m)System.out.println(String.valueOf(q));}

Indented:
static void f(String s) {
    int y = s.length(), x = 0;
    char[][] m = new char[y][y];
    for(char[] q : m)
        java.util.Arrays.fill(q, ' ');
    y = 0;
    for(char c : s.toCharArray())
        if(c == '(')
            m[y++][x++] = c;
        else
            m[--y][x++] = c;
    for(char[] q : m)
        System.out.println(String.valueOf(q));
}

I know it's been more than a year, but "I guess the final loop could be shortened, but I'll leave it as an exercise to the reader. ;-)"; you're indeed right. It can be changed from for(x=0;x<l*l;x++)System.out.print((x%l==0?"\n":"")+m[x]); to for(x=0;x<l*l;)System.out.print((x%l==0?"\n":"")+m[x++]); for -1 byte. Also, you can save 2 more bytes by removing p=x=0 and just use int p=0,x=0, at initialization of the fields instead. In total it becomes 211 bytes.

C, 118 117 Bytes
Another answer in C, but mine is shorter.
c;d;main(m,v)int**v;{while(d++<m){char*p=v[1];while(*p)c+=*p==40,putchar(c-d?*p:32),m=c>m?c:m,c-=*p++==41;puts("");}}

Ungolfed version:
c; /* current depth */
d; /* depth to print in current row */
main(m,v)int**v;{
    while(d++<m) {
        char*p=v[1];
        while(*p){
            c+=*p==40;           /* 40 = '(' */
            putchar(c-d?*p:32); /* 32 = ' ' (space) */
            m=c>m?c:m;           /* search maximum depth */
            c-=*p++==41;         /* 41 = ')' */
        }
        puts("");
    }
}

And it works!
% ./telescope '()(())((()))(())()'
()(  )(    )(  )()
   ()  (  )  ()
        ()
% ./telescope '((()())()(()(())()))'
(                  )
 (    )()(        )
  ()()    ()(  )()
             ()

Quite an elegant solution, however putchar(c-d?32:*p) is one character shorter than putchar(c==d?*p:32) .

Batch, 424 bytes
@echo off
setLocal enableDelayedExpansion
set s=%1
set a=1
:c
if defined s (set/ac+=1
set "z="
if "%s:~0,1%"=="(" (set "1=(")else (set/aa-=1
set "1=)")
for %%a in (!a!)do for /f usebackq %%b in (`powershell "'!l%%a!'".Length`)do (set/ay=!c!-%%b
for /l %%a in (1,1,!y!)do set z= !z!
set "l%%a=!l%%a!!z!!1!")
if "%s:~0,1%"=="(" set/aa+=1
if !a! GTR !l! set/al=!a!-1
set "s=%s:~1%"
goto c)
for /l %%a in (1,1,!l!)do echo !l%%a!

Un-golfed:
@echo off
setLocal enableDelayedExpansion

set s=%1
set a=1
set c=0
set l=0

:c
if defined s (
    set /a c+=1
    set "z="
    if "%s:~0,1%"=="(" (
        set "1=("
    ) else (
        set /a a-=1
        set "1=)"
    )
    for %%a in (!a!) do for /f usebackq %%b in (`powershell "'!l%%a!'".Length`) do (
        set /a y=!c!-%%b
        for /l %%a in (1,1,!y!) do set z= !z!
        set "l%%a=!l%%a!!z!!1!"
    )
    if "%s:~0,1%"=="(" set /a a+=1
    if !a! GTR !l! set /a l=!a!-1
    set "s=%s:~1%"
    goto c
)

for /l %%a in (1,1,!l!) do echo !l%%a!

Example:
h:\>par.bat (((())())(()))
 (            )
  (      )(  )
   (  )()  ()
    ()

-1 bytes: usebackq => useback

C#, 195 bytes
First try at golf - yell if I did something wrong.
Alternative C# version using SetCursorPosition and working left to right taking the input as a commandline arg.
using System;class P{static void Main(string[] a){Action<int,int>p=Console.SetCursorPosition;int r=0,c=0;foreach(var x in a[0]){r+=x==')'?-1:0;p(c,r);Console.Write(x);r+=x=='('?1:0;p(c,r);c++;}}}

I thought it would be fun to adjust the write position based on the open/close paren and not full lines.  Close paren moves the position up before writing; open paren moves it down after writing.  Actioning SetCursorPosition saves five bytes.  Moving the cursor to the next line after the output would take quite a bit extra.
using System;
class P
{
    static void Main(string[] a)
    {
        Action<int, int> p = Console.SetCursorPosition;
        int r = 0, c = 0;
        foreach (var x in a[0])
        {
            r += x == ')' ? -1 : 0;
            p(c, r);
            Console.Write(x);
            r += x == '(' ? 1 : 0;
            p(c, r);
            c++;
        }
    }
}

Batch, 356 335 bytes
I know that there already exists a Batch solution for this challenge, but this one is golfed significantly more and seems to take a different approach. Most importantly, the other batch solution contains at least one powershell command; this solution does not.
@echo off
setlocal enabledelayedexpansion
set p=%1
set p=%p:(="(",%
set p=%p:)=")",%
set c=0
for %%a in (%p%)do (if ")"==%%a set/ac-=1
set d=!d!,!c!%%~a
if "("==%%a set/ac+=1&if !c! GTR !m! set m=!c!)
set/am-=1
for /l %%a in (0,1,!m!)do (for %%b in (!d!)do (set t=%%b
if "%%a"=="!t:~0,-1!" (cd|set/p=!t:~-1!)else (cd|set/p=. ))
echo.)

There is a  backspace character (U+0008) on the second to last line following the dot (line 12, column 57). This isn't visible in the code posted here but is included in the byte count.

Somebody else actually submitting an answer in Batch - Nice one +1.

Haskell, 107 bytes
h#('(':s)=h:(h+1)#s
h#(_:s)|k<-h-1=k:k#s
_#_=[]
g s=[do(c,i)<-zip s$0#s;max" "[c|i==h]|h<-[0..maximum$0#s]]

Try it online!
Based on d8d0d65b3f7cf42's Haskell answer.

Haskell, 227 bytes
n _ []=[]
n h ('(':r)=('(',h):n(h+1)r
n d (')':r)=let h=d-1 in(')',h):n h r
m n []=n
m n ((_,h):r)=m(max h n)r
p s=let v=n 0 s;h=m 0 v;in map(\d->map(\(b,l)->if l==d then b else ' ')v)[0..h]
main=fmap p getLine>>=mapM_ putStrLn

You can save a few spaces with operators: e.g. n#[] instead of m n [].

Perl, 76 bytes
$a[/\(/?$l++:--$l][$i++]=$_ for split//,<>;print map{$_||' '}@$_,"\n"for@a

No use strict here :)

Lex, 94 bytes
Depends on Linux console codes. With gcc, you can cut out four bytes by replacing both instances of \33 with an actual escape character.
%%
 int p[2]={0};
\( printf("(\33D");++p[!*p];
\) printf("\33M)");--*p;
\n while(p[1]--)ECHO;

To compile and run:
$ flex -o telescopic.c telescopic.l
$ gcc -o telecopic telescopic.c -lfl
$ ./telescopic
(()(()())()((())))(())
(                )(  )
 ()(    )()(    )  ()
    ()()    (  )
             ()
--- type ctrl-D ---

Python 2, 166 bytes
Not much to be said:
m,c,l=list(input()),0,[]
for j in m:c+=1if j=='('else-1;l+=[c-1if j=='('else c]
for i in range(max(l)+1):
 t,p='',0
 for q in m:t+=q if l[p]==i else' ';p+=1
 print t

Jelly, 15 bytes
OḂ-*Ä+ƲṬ€z0ao⁶Y

Try it online!
Went through quite a few 16-byters before arriving at this...
O                  Codepoints
 Ḃ                 mod 2. ('(' -> 0, ')' -> 1)
    Ä              Cumulative sums of
  -*               -1 to the power of each,
     +Ʋ            plus the corresponding original residues.
       Ṭ€          For each, an array with 1 at that index and 0 elsewhere.
         z0        Zip filling with zeroes,
           a       replace ones with corresponding elements of the input string,
            o⁶     replace zeroes with spaces,
              Y    join on newlines.

K (ngn/k), 29 bytes
{+(|/i)$(-i:m-+\m-~m:2!x)$'x}

Try it online!

(...)$'x left-pad each character of the input by the corresponding number of spaces

m:2!x take the input string mod 2 and store in m; translates "(" into 0 and ")" into 1
m-~m convert 0s to -1s (leaving 1s as-is)
i:m-+\ calculate the "depth" of each character, storing in i
-i negate to left-pad (positive numbers will right-pad)

+(|/i)$ right-pad each string with spaces to the same length, then transpose the result

IDL 8.4, 173 177 bytes
This is similar enough to the formatter challenge that I had half a solution already. IDL is still a terrible golfing language, but I'm pretty happy with how this worked out.
read,(p='')&a=[0:strlen(p)-1]&c=strmid(p,a,1)&e=c.map(lambda(x,d:'('eq x:d++:d---1)))&print,[0:max(e)].map(lambda(x,y,z:y.reduce(lambda(t,u,v,w,:t+(w eq v?u:' ')),x,z),c,a))&end

Un-golfed:
read,(p='') ;read a string from input
a=[0:strlen(p)-1] ;index array to the input
c=strmid(p,a,1) ;split the input into an array of 1-char substrings
e=c.map(lambda(x,d:'('eq x:d++:d---1))) ;for each substring, increment depth if ( and decrement otherwise, saving depth each time
print,[0:max(e)].map(lambda(x,y,z:y.reduce(lambda(t,u,v,w,:t+(w eq v?u:' ')),x,z),c,a)) ;print an array of strings, each one including the parens in that depth level.
end ;end the script

C#, 196 bytes
Very simple complete program that takes input via STDIN, and outputs to STDOUT. I should like to get rid of the S.Length, but haven't found a way that pays.
using Q=System.Console;class P{static void Main(){var S=Q.ReadLine();for(int i=0,c;++i<S.Length;){var r="";c=0;foreach(var k in S)r+=(c+=81-k*2)+k-40==i?k:' ';if(r.Contains("("))Q.WriteLine(r);}}}

It simply iterates over the input a number of times (input length - 1), keeping track of the parentheses "depth", and comparing it to the current iteration count (i) - if they match, then it adds the current parenthesis to a string, to be printed at the end of the iteration. Because more iterations may be done than necessary, it only prints the iteration result (r) if it contains a parenthesis.
using Q=System.Console;

class P
{
    static void Main()
    {
        var S=Q.ReadLine(); // read input

        for(int i=0,c;
            ++i<S.Length; // can't be more than S.Length - 1 lines of output
            )
        {
            var r=""; // reset result
            c=0; // current paren depth
            foreach(var k in S) // for each char in input
                r+= // append something...
                    (c+=81-k*2) // move c
                    +k-40==i? // check if we should output the current char
                        k:
                        ' '; // otherwise a space
            if(r.Contains("(")) // only print if there is some content
                Q.WriteLine(r);
        }
    }
}

MATL, 42 41 bytes
Uses current version (4.0.0) of the language, which is newer than this challenge (but the challenge was so attractive...)
j32-t8=2*1-TTo3X53$X+ZSYsP0hP1+wtn:wZ?32+c

EDIT (May 20, 2016): Try it online! with X+ replaced by Y+, according to version 18.0.0 of the language.
Example
>> matl j32-t8=2*1-TTo3X53$X+ZSYs0wh1+wtn:wZ?32+c
> ()(())((()))(())()
()(  )(    )(  )()
   ()  (  )  ()
        ()

Explanation
The general idea is to use convolution to analyze pairs of consecutive symbols. There are four possible pairs:

((: the second symbol should be on a lower line than the first
)): the second symbol should be on a higher line than the first
() or )(: the second symbol should be on the same line as the first

When analyzing each pair, the line of the first symbol is already known, and the analysis tells the line of the second. Then the nex pair is analyzed, obtained by advancing one symbol, that is, with overlapping.
j           % input string
32          % ASCII code of space character
-           % subtraction. Will give 8 or 9 for '(' and ')'
t8=         % 1 for '(' symbols, 0 for ')'
2*1-        % convert into 1 / -1
TTo         % array [1 1] (for convolution)
3X5         % 'valid' flag for convolution
3$          % specify three inputs for convolution
X+          % convolution
ZS          % sign function
Ys          % cumulative sum
0wh         % prepend a 0
1+          % add 1. This gives line number of each symbol
wtn:w       % Vector [1 2 ... n] where n is string length. Rearrange
Z?          % create (sparse) matrix with three inputs: row, col, val
32+c        % add space code and convert to chat

JavaScript (Node.js), 71 bytes
x=>[...x].map((_,n,s)=>s.map(c=>(c=='('?n--:++n)?' ':c).join``).join`
`

Try it online!
JavaScript (Node.js), 85 bytes, just enough lines
x=>[...x].map((_,n,s)=>(Q=s.map(c=>(c=='('?n--:++n)?' ':c).join``)<1?'':Q+`
`).join``

Try it online!

Invalid, "You may optionally print a single trailing newline."

Charcoal, 12 bytes
ＦＳ¿⁼(ι↘(«Ｍ↑)

Try it online!
Explanation
ＦＳ             For each character in next input as string
    ¿⁼(ι         If character is "("
        ↘(       Print "(" down and to the right - this is equivalent to printing "(" and moving down
          «Ｍ↑)  Else move up and print ")"

Haskell, 117 114 bytes
f(y:b)|a<-sum[1|y=='(']=a:map(+(2*a-1))(f b)
f[]=[]
p s=[[last$' ':[a|b==i]|(b,a)<-zip(f s)s]|i<-[1..maximum$f s]]

Try it online!

C, 94 99 97 96
i,j,k,l;f(char*s){for(l=0;!i--;l-=puts(""))for(j=0;k=s[j++];putchar((k&1?--l:l++)?32:k))i&=l<2;}

Pure C version that doesn't use the consoles escape codes. Ungolfed:
i,j,k,l;                 // stop,iterator,current char,level
f(char*s){
  for(l=0;               // reset level
      !i--;              // stop ? return : stop = 1;
      l-=puts(""))      // new line + next level
    for(j=0;
        k=s[j++];        // for each char
        putchar(
          (k&1?--l:l++)  // char == 41 ? prev level : next level
          ?32:k))        // only print brackets at level 0
      i&=l<2;            // if level > 1 then don't stop
}

Try it online!
Changelog:

+5 Byte Temporary fix to match rules
-2 Byte Switch !i++ to !i-- drops the need to reset i
-1 Byte Switch puts(""),--l to l-=puts("") Thanks to @ceilingcat

I'm unable to find the relevant meta-post, but I'm pretty sure functions should be self-contained when run multiple times. So I think you should add i=j=k=l=0 to your code instead of resetting them in your main-method. I'll see if I can find the meta-post to explain it more clearly though, but I've had other people make these kind of comments on my answers in the past.. Nice answer nonetheless, so +1 from me.

@KevinCruijssen Here it is Edit: mwahahaha

Found the meta-post, and here another relevant one. EDIT: @JoKing You beat me to it by 10 sec. ;)

@KevinCruijssen A damn you're right what a sad day. Temp fix it at the cost of 5 byte. Hopefully I can get rid of some of them again. Ideas ? ;)

@Christoph Unfortunately I don't see anything to golf (although there might of course be). I'm not too skilled in C to be completely honest. It seems already pretty well-golfed to me, hence the upvote I gave. ;)

@ceilingcat Nice one! Its only guaranteed to return a non negative number but it seems to return 1 in this case on tio :) Thanks!

VIM, 101 bytes
↵ = Enter
qwlmto<esc>`t@wq@w:s/()/(*)/g↵:set ve=all↵:set nows:↵set nosol↵qqvi)ygvr jPk/(↵@qq@qjjdGqeGl?*↵<C-V>ggoGr|@eq@e:%s/|//↵

Retina, 65 bytes
./\S/{*\`\(((?<-2>(\()*\))*)\)
($.1* )
\(((?<-2>(\()*\))*)\)
 $1

Try it online! Note: Trailing space. Link includes test cases. Explanation:
.

Don't print the spaces left over at the end.
/\S/{

Repeat until there are only spaces left.
*\`

Print the result of this substitution without changing the current value.
\(((?<-2>(\()*\))*)\)
($.1* )

Match pairs of balanced parentheses and replace their content with a run of spaces of the same length.
\(((?<-2>(\()*\))*)\)
 $1

Match balanced parentheses and replace the outer pairs with spaces.
For Retina 0.8.2 you have the choice of this 60 byte code:
{*`\(((?<-2>(\()*\))*)\)
($.1$* )
\(((?<-2>(\()*\))*)\)
 $1

Try it online! Note: Trailing space. Link includes test cases. Explanation: The differences are as follows:

Retina 0.8.2 doesn't have a while loop, only a convergence loop. However, this ends up printing blank lines while waiting for the loop to converge.
Retina 0.8.2 uses * for much the same effect as .*\.
Retina 0.8.2 uses $* instead of * in the replacement.

Alternatively, if the blank lines are a problem, you can use this 92 byte code:
{`.+$
$&¶$&
\(((?<-2>(\()*\))*)\)(?=.*¶.*$)
($.1$* )
\(((?<-2>(\()*\))*)\)(?=.*$)
 $1
¶ +$

Try it online! Link includes test cases. Explanation:
{`

Repeat until the value converges.
.+$
$&¶$&

Duplicate the last line.
\(((?<-2>(\()*\))*)\)(?=.*¶.*$)
($.1$* )

Match pairs of balanced parentheses on what used to be the last line and replace their content with a run of spaces of the same length.
\(((?<-2>(\()*\))*)\)(?=.*$)
 $1

Match pairs of balanced parentheses on the last line and replace the outer pairs with spaces.
¶ +$

Delete the last line if it's only spaces. This allows the loop to terminate.

Haskell, 96 bytes
f s=fst$span(any(>' '))[do
c:d<-scanr(:)[]s
max" "[c|sum[1|')'<-d]-sum[1|'('<-c:d]==i]|i<-[0..]]

Try it online!

How does this work? I can’t really read Haskell but this looks cool

Japt -Rx, 17 bytes
¬£®¥'(?Y´:°Y ?S:Z

Try it online!
Unpacked & How it works
Uq mXYZ{UmZ{Z=='(?Y--:++Y ?S:Z

Uq      Convert the input string into array of chars
mXYZ{   Map with the function...
          Here, Y (index) is used as the desired level of "telescoping"
UmZ{      Map on the original input string with the function...
Z=='(?      If this char is "("...
Y--:          Decrement Y
++Y           Otherwise, increment Y
?           If Y is nonzero (i.e. this char is *not* at desired level)...
S:            Replace with a space
Z             Otherwise, use the char as-is

Flags:
-R      Join the resulting array with newline
-x      Trim the resulting string on both ends

Ported from @l4m2's JS solution. It actually fits into Japt's built-ins quite nicely, and trailing whitespaces can be conveniently removed with the use of -x flag.

Vyxal j, 27 bytes
ƛC∷&-¥n꘍nC₂&+;:vLG£ƛ¥↲;ÞTv∑

Try it Online!
A mess that I'm proud of. Thanks to lyxal for fixing a bug.

Swift 5.9, 149 bytes
var c=0,d=[0],t={i in(i+"",d=i.map{$0<")" ?(c,c+=1).0:(c-=1,c).1},{(0...d.max()!).map{e in.init(zip(i,d).map{$0.1==e ?$0.0:" "})}.joined}()("\n")).2}

I love it when I can shove everything into a single line of code (i.e. without using semicolons; I prefer to use newlines instead since they don't incur a byte penalty in Swift). map(_:) FTW! (Although, to be fair, tuple shenanigans make this relatively easy too...)
Here's the original, with an explanation (and a JDoodle link):
func telescope(_ input: String) -> String {
    // As an example, we'll pretend that `input` is
    // this string: "((()())()(()(())()))"

    // MARK: - Depth Calculation

    var currentDepth = 0
    let depths = input.map { character in
        switch character {
        // This is essentially equivalent to `currentDepth++`,
        // if that operator still existed in Swift (remember,
        // that one returns the value *before* incrementing).
        case "(": (currentDepth, currentDepth += 1).0

        // Likewise, this would be the same as `--currentDepth`
        // (the one that returns the value *after* decrementing).
        case ")": (currentDepth -= 1, currentDepth).1

        // If it isn't a parenthesis, we have some invalid input.
        default: fatalError("wtf?!?! that ain't a valid string!")
        }
    }

    // Now, for our example, `depths` is:
    // [0, 1, 2, 2, 2, 2, 1, 1, 1, 1, 2, 2, 2, 3, 3, 2, 2, 2, 1, 0]
    // (note that a depth of 0 is the topmost/outermost level)

    // Here's an alternative representation:
    // ((()())()(()(())()))
    // 01222211112223322210

    // MARK: - Tier Generation

    let depthRange = 0...depths.max()!
    let tiers = depthRange.map { depth in
        let inputWithDepths = zip(input, depths)
        let charactersOnThisTier = inputWithDepths.map { (character, otherDepth) in
            // If this character is on this tier, show it; otherwise, add a space.
            otherDepth == depth ? character : " "
        }
        return charactersOnThisTier
    }

    // MARK: - Joining

    let joinedTiers = tiers.map { String($0) }.joined(separator: "\n")
    return joinedTiers
}

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


text:
Tiling a 2^N by 2^N Grid with L-Shaped Trominoes
When students are first taught about the proof technique of mathematical induction, a common example is the problem of tiling a 2N×2N grid with L-shaped trominoes, leaving one predetermined grid space empty. (N is some nonnegative integer.)
I will leave it to you to go over the proof if you do not already know it. There are many resources that discuss it.
Your task here is to write a program that takes in a value for N, as well as the coordinates of the grid space to leave empty, and prints an ASCII representation of the resulting tromino tiled grid.
The character O will fill the empty space, and the 4 rotations of our tromino will look like this:
|
+-

 |
-+

-+
 |

+-
|

(Yes, it can be ambiguous which + goes with which - and | for certain arrangements, but that's ok.)
Your program must work for N = 0 (for a 1×1 grid) up to at least N = 8 (for a 256×256 grid). It will be given x and y values that are the coordinates for the O:

x is the horizontal axis. x = 1 is the left grid edge, x = 2N is the right grid edge.
y is the vertical axis. y = 1 is the top grid edge, y = 2N is the bottom grid edge.

Both x and y are always in the range [1, 2N].
So for a given N, x, and y, your program must print a 2N×2N grid, tiled completely with L-shaped trominoes, except for the x, y grid coordinate which will be an O.
Examples
If N = 0, then x and y must both be 1. The output is simply
O

If N = 1, x = 1, and y = 2, the output would be
-+
O|

N = 2, x = 3, y = 2:
+--+
||O|
|+-|
+--+

N = 2, x = 4, y = 1:
+-|O
||+-
|+-|
+--+

N = 3, x = 3, y = 6 (e.g. the image on this page):
+--++--+
|+-||-+|
||+--+||
+-|-+|-+
+--+||-+
||O|-+||
|+-||-+|
+--++--+

Details

You may write a function that takes the 3 integers instead of writing an entire program. It should print or return the grid string.
Take input from stdin, command line, (or function args if you write function).
The output may optionally contain a single training newline.
You are not required to use the tiling method that the proof normally suggests. It only matters that the grid is filled with L-shaped trominoes besides the O. (Trominoes may not be cut or go out of the grid bounds.)

The shortest code in bytes wins. Tiebreaker is earlier post. (Handy byte counter.)

Haskell, 250 240 236 bytes
c=cycle
z o(#)(x,y)=zipWith o(1#x)(2#y)
f n x y=unlines$(z(+)(\m w->[c[0,m]!!div(w-1)(2^(n-k))|k<-[1..n]])(x,y),"O")%n
(_,x)%0=[x]
((p:o),x)%k=z(++)(\_ q->((o,x):c[(c[3-q],[" |-+| +--+ |+-|"!!(4*p+q)])])!!abs(p-q)%(k-1))=<<[(0,1),(2,3)]

This follows the inductive solution to the problem closely. The point to mark is represented by a sequence of numbers from 0 to 3 which indicate which quadrant holds the point at each zoom level; this is initially calculated by the expression starting with z(+). The operator (%) combines pictures for the four quadrants into a single picture. Pictures for the unmarked quadrants are generated by drawing marked quadrants with the mark somewhere near the middle, drawn with a mark of "+-|" as appropriate to build the central L tile.
Funny business: For golf reasons, the subexpression
\m w->[c[0,m]!!div(w-1)(2^(n-k))|k<-[1..n]]

(which more or less computes the bit sequence for a number) is hilariously inefficient --- it determines if w / 2^p is odd or even by looking up the (w / 2^p)th element of a list.
Edit: Saved 10 bytes by inlining the bit calculation and replacing an if/then/else with an indexing operation.
Edit2: Saved four more bytes by switching a function back to an operator.
@randomra, the race is on!
Demo:
λ> putStr $ f 4 5 6
+--++--++--++--+
|+-||-+||+-||-+|
||+--+||||+--+||
+-|+-|-++-|-+|-+
+-||-+-++--+||-+
||+-O||||-+|-+||
|+-||-+|-+|||-+|
+--++--+||-++--+
+--++-|-+|-++--+
|+-|||+--+|||-+|
||+-|+-||-+|-+||
+-||+--++--+||-+
+-|+-|-++-|-+|-+
||+--+||||+--+||
|+-||-+||+-||-+|
+--++--++--++--+

C, 399 bytes
char*T=" |-+ | +-| ",*B;w;f(N,x,y,m,n,F,h,k,i,j){w=B?F=0,w:1<<N|1;char b[N?w*w:6];for(k=w;k--;)b[k*w-1]=10;B=!B?F=1,m=0,n=0,x--,y--,b:B;if(N>1){h=1<<N-1;i=x>--h,j=y>h;while(++k<4)if(k%2-i||k/2-j)f(N-1,!(k%2)*h,!(k/2)*h,m+k%2*(h+1),n+k/2*(h+1));f(1,h&i,h&j,m+h,n+h);h++;f(N-1,x-h*i,y-h*j,m+h*i,n+h*j);}else while(++k<4)B[w*(n+k/2)+m+k%2]=T[5*x+2*y+k];if(F)B[y*w+x]=79,B[w*w-w-1]=0,puts(N?B:"O"),B=0;}

No one's come forward with anything yet, so I'll offer up a meager solution. Mark my words, this is not the end. This will get shorter.
We define a function f that takes 10 arguments, but you need only call it with f(N, X, Y). Output goes to stdout.
Here's a readable version:
char*T=" |-+ | +-| ",*B;
w;
f(N,x,y,m,n,F,h,k,i,j){
    w=B?F=0,w:1<<N|1;
    char b[N?w*w:6];
    for(k=w;k--;)
        b[k*w-1]=10;
    B=!B?F=1,m=0,n=0,x--,y--,b:B;
    if(N>1){
        h=1<<N-1;
        i=x>--h,j=y>h;
        while(++k<4)
            if(k%2-i||k/2-j)
                f(N-1,!(k%2)*h,!(k/2)*h,m+k%2*(h+1),n+k/2*(h+1));
        f(1,h&i,h&j,m+h,n+h);
        h++;
        f(N-1,x-h*i,y-h*j,m+h*i,n+h*j);
    }
    else
        while(++k<4)
            B[w*(n+k/2)+m+k%2]=T[5*x+2*y+k];
    if(F)B[y*w+x]=79,B[w*w-w-1]=0,puts(N?B:"O"),B=0;
}

A taste of output for f(3, 2, 7):
+--++--+
|+-||-+|
||+--+||
+-|-+|-+
+--+||-+
|-+|-+||
|O|||-+|
+--++--+

It's a fairly simple recursive algorithm to fill the grid. I may upload an animation of the algorithm drawing trominoes since I think it's pretty neat. As usual, feel free to ask questions and shout at me if my code breaks!
Try it online!

Python 3, 276 265 237 bytes
My first Python golf so I'm sure there is a lot of room for improvement.
def f(n,x,y,c='O'):
 if n<1:return c
 *t,l,a='x|-+-|',2**~-n;p=(a<x)+(a<y)*2
 for i in 0,1,2,3:t+=(p-i and f(n-1,1+~i%2*~-a,1+~-a*(1-i//2),l[p+i])or f(n-1,1+~-x%a,1+~-y%a,c)).split(),
 u,v,w,z=t;return'\n'.join(map(''.join,zip(u+w,v+z)))

10 bytes saved thanks to @xnor and 6 more bytes thanks to @Sp3000.
The function returns a string. Example usage:
>>>print(f(3,3,6))
+--++--+
|+-||-+|
||+--+||
+-|-+|-+
+--+||-+
||O|-+||
|+-||-+|
+--++--+

An impressive first run at Python golfing! Some quick charsaves. You can cut the space before if p!=i; the list inside .join() doesn't need []; (1-i%2) can be done as ~i%2; you can use iterable unpacking to write t,l,a=[],... as *t,l,a=...;  if n==0 can be checked as if n<1 because n can't be negative; the final "\n".join can probably be done by printing each element, since general rules allow printing in place of returning; if p!=i can be if p-i because nonzero values are Truthy.

@xnor Thanks for the tips! The unpacking to get an implicit empty list is very neat. I use return instead of print as f is a recursive function. I actually have to revert the output formatting with split() after every self-call.

A few more: The last line can be written as A,B,C,D=t;return'\n'.join(map("".join,zip(A+C,B+D))), t+=[...] on the second-last line can be written as t+=..., (adding a tuple instead of a list) and I'm not sure if this one works but A if B else C can be written as B and A or C (also on the second-last line), but only if A is never falsy (which I don't think it is?)

JavaScript (ES6) 317 414
A lot of work to golf, but still quite long.
T=(b,x,y)=>
  (F=(d,x,y,f,t=[],q=y<=(d>>=1)|0,
      b=d?x>d
       ?q
         ?F(d,x-d,y,0,F(d,1,1,2))
         :F(d,1,d,2,F(d,x-d,y-d))
       :F(d,1,d,1-q,F(d,1,1,q)):0,
      r=d?(x>d
         ?F(d,d,d,1-q,F(d,d,1,q))
         :q
           ?F(d,x,y,1,F(d,d,1,2))
           :F(d,d,d,2,F(d,x,y-d))
      ).map((x,i)=>x.concat(b[i])):[[]]
    )=>(r[y-1][x-1]='|+-O'[f],r.concat(t))
  )(1<
  (F=(d,x,y,f,t=[],q=y<=(d>>=1)|0,
      b=d?x>d
       ?q
         ?F(d,x-d,y,0,F(d,1,1,6))
         :F(d,1,d,6,F(d,x-d,y-d))
       :F(d,1,d,q,F(d,1,1,q+1)):0,
      r=d?(x>d
         ?F(d,d,d,q+3,F(d,d,1,q+4))
         :q
           ?F(d,x,y,1,F(d,d,1,6))
           :F(d,d,d,6,F(d,x,y-d))
      ).map((x,i)=>x.concat(b[i])):[[]]
    )=>(
    r[y-1][x-1]='┐│┘┌│└─O'[f],r.concat(t)
  ))(1<{
  var x=X.value|0, y=Y.value|0, n=N.value|0;

  var b=1<<n, cur=1<<(n+n);
  (L=_=>{
    --cur;
    O.innerHTML=T(n,(cur&(b-1))+1,(cur>>n)+1);
    cur&&setTimeout(L,100);
  })()
}

tile=_=>{
  var x=X.value|0, y=Y.value|0, n=N.value|0;
  O.innerHTML=T(n,x,y);
}

tile()
input { width: 3em }
pre { font-size: 10px; line-height: 10px }
N: <input id=N value=4> X: <input id=X value=5> Y: <input id=Y value=3>
<button onclick="tile()">Tile</button>
<button onclick="loop()">Loop</button>

IDL 8.3+, 293 bytes
This is too long, I'm trying to cut it down but I haven't gotten there yet.
function t,n,x,y
m=2^n
c=['|','+','-']
b=replicate('0',m,m)
if m eq 1 then return,b
h=m/2
g=h-1
k=[1:h]
o=x gt h
p=y gt h
q=o+2*p
if m gt 2then for i=0,1 do for j=0,1 do b[i*h:i*h+g,j*h:j*h+g]=t(n-1,i+2*j eq q?x-i*h:k[i-1],i+2*j eq q?y-j*h:k[j-1])
b[g+[1-o,1-o,o],g+[p,1-p,1-p]]=c
return,b
end

Outputs:
IDL> print,t(1,1,2)
- +
0 |
IDL> print,t(2,3,2)
+ - - +
| | 0 |
| + - |
+ - - +
IDL> print,t(2,4,1)
+ - | 0
| | + -
| + - |
+ - - +
IDL> print,t(3,3,6)
+ - - + + - - +
| + - | | - + |
| | + - - + | |
+ - | - + | - +
+ - - + | | - +
| | 0 | - + | |
| + - | | - + |
+ - - + + - - +

And, uh... just for fun...
IDL> print,t(6,8,9)
+ - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - +
| + - | | - + | | + - | | - + | | + - | | - + | | + - | | - + | | + - | | - + | | + - | | - + | | + - | | - + | | + - | | - + |
| | + - - + | | | | + - - + | | | | + - - + | | | | + - - + | | | | + - - + | | | | + - - + | | | | + - - + | | | | + - - + | |
+ - | + - | - + + - | - + | - + + - | + - | - + + - | - + | - + + - | + - | - + + - | - + | - + + - | + - | - + + - | - + | - +
+ - | | + - - + + - - + | | - + + - | | + - - + + - - + | | - + + - | | + - - + + - - + | | - + + - | | + - - + + - - + | | - +
| | + - | + - | | - + | - + | | | | + - | + - | | - + | - + | | | | + - | + - | | - + | - + | | | | + - | + - | | - + | - + | |
| + - | | | + - - + | | | - + | | + - | | | + - - + | | | - + | | + - | | | + - - + | | | - + | | + - | | | + - - + | | | - + |
+ - - + + - | - + | - + + - - + + - - + + - | - + | - + + - - + + - - + + - | + - | - + + - - + + - - + + - | - + | - + + - - +
+ - - + + - | 0 | | - + + - - + + - - + + - - + | | - + + - - + + - - + + - | | + - - + + - - + + - - + + - - + | | - + + - - +
| + - | | | + - - + | | | - + | | + - | | - + | - + | | | - + | | + - | | | + - | + - | | - + | | + - | | - + | - + | | | - + |
| | + - | + - | | - + | - + | | | | + - - + | | | - + | - + | | | | + - | + - | | | + - - + | | | | + - - + | | | - + | - + | |
+ - | | + - - + + - - + | | - + + - | - + | - + + - - + | | - + + - | | + - - + + - | + - | - + + - | - + | - + + - - + | | - +
+ - | + - | - + + - | - + | - + + - - + | | - + + - | - + | - + + - | + - | - + + - | | + - - + + - - + | | - + + - | - + | - +
| | + - - + | | | | + - - + | | | - + | - + | | | | + - - + | | | | + - - + | | | | + - | + - | | - + | - + | | | | + - - + | |
| + - | | - + | | + - | | - + | - + | | | - + | | + - | | - + | | + - | | - + | | + - | | | + - - + | | | - + | | + - | | - + |
+ - - + + - - + + - - + + - - + | | - + + - - + + - - + + - - + + - - + + - - + + - - + + - | - + | - + + - - + + - - + + - - +
+ - - + + - - + + - - + + - | - + | - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + | | - + + - - + + - - + + - - +
| + - | | - + | | + - | | | + - - + | | | - + | | + - | | - + | | + - | | - + | | + - | | - + | - + | | | - + | | + - | | - + |
| | + - - + | | | | + - | + - | | - + | - + | | | | + - - + | | | | + - - + | | | | + - - + | | | - + | - + | | | | + - - + | |
+ - | + - | - + + - | | + - - + + - - + | | - + + - | - + | - + + - | + - | - + + - | - + | - + + - - + | | - + + - | - + | - +
+ - | | + - - + + - | + - | - + + - | - + | - + + - - + | | - + + - | | + - - + + - - + | | - + + - | - + | - + + - - + | | - +
| | + - | + - | | | + - - + | | | | + - - + | | | - + | - + | | | | + - | + - | | - + | - + | | | | + - - + | | | - + | - + | |
| + - | | | + - | + - | | - + | | + - | | - + | - + | | | - + | | + - | | | + - - + | | | - + | | + - | | - + | - + | | | - + |
+ - - + + - | | + - - + + - - + + - - + + - - + | | - + + - - + + - - + + - | - + | - + + - - + + - - + + - - + | | - + + - - +
+ - - + + - | + - | - + + - - + + - - + + - | - + | - + + - - + + - - + + - - + | | - + + - - + + - - + + - | - + | - + + - - +
| + - | | | + - - + | | | - + | | + - | | | + - - + | | | - + | | + - | | - + | - + | | | - + | | + - | | | + - - + | | | - + |
| | + - | + - | | - + | - + | | | | + - | + - | | - + | - + | | | | + - - + | | | - + | - + | | | | + - | + - | | - + | - + | |
+ - | | + - - + + - - + | | - + + - | | + - - + + - - + | | - + + - | - + | - + + - - + | | - + + - | | + - - + + - - + | | - +
+ - | + - | - + + - | - + | - + + - | + - | - + + - | - + | - + + - - + | | - + + - | - + | - + + - | + - | - + + - | - + | - +
| | + - - + | | | | + - - + | | | | + - - + | | | | + - - + | | | - + | - + | | | | + - - + | | | | + - - + | | | | + - - + | |
| + - | | - + | | + - | | - + | | + - | | - + | | + - | | - + | - + | | | - + | | + - | | - + | | + - | | - + | | + - | | - + |
+ - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + | | - + + - - + + - - + + - - + + - - + + - - + + - - + + - - +
+ - - + + - - + + - - + + - - + + - - + + - - + + - - + + - | - + | - + + - - + + - - + + - - + + - - + + - - + + - - + + - - +
| + - | | - + | | + - | | - + | | + - | | - + | | + - | | | + - - + | | | - + | | + - | | - + | | + - | | - + | | + - | | - + |
| | + - - + | | | | + - - + | | | | + - - + | | | | + - | + - | | - + | - + | | | | + - - + | | | | + - - + | | | | + - - + | |
+ - | + - | - + + - | - + | - + + - | + - | - + + - | | + - - + + - - + | | - + + - | - + | - + + - | + - | - + + - | - + | - +
+ - | | + - - + + - - + | | - + + - | | + - - + + - | + - | - + + - | - + | - + + - - + | | - + + - | | + - - + + - - + | | - +
| | + - | + - | | - + | - + | | | | + - | + - | | | + - - + | | | | + - - + | | | - + | - + | | | | + - | + - | | - + | - + | |
| + - | | | + - - + | | | - + | | + - | | | + - | + - | | - + | | + - | | - + | - + | | | - + | | + - | | | + - - + | | | - + |
+ - - + + - | + - | - + + - - + + - - + + - | | + - - + + - - + + - - + + - - + | | - + + - - + + - - + + - | - + | - + + - - +
+ - - + + - | | + - - + + - - + + - - + + - | + - | - + + - - + + - - + + - | - + | - + + - - + + - - + + - - + | | - + + - - +
| + - | | | + - | + - | | - + | | + - | | | + - - + | | | - + | | + - | | | + - - + | | | - + | | + - | | - + | - + | | | - + |
| | + - | + - | | | + - - + | | | | + - | + - | | - + | - + | | | | + - | + - | | - + | - + | | | | + - - + | | | - + | - + | |
+ - | | + - - + + - | + - | - + + - | | + - - + + - - + | | - + + - | | + - - + + - - + | | - + + - | - + | - + + - - + | | - +
+ - | + - | - + + - | | + - - + + - | + - | - + + - | - + | - + + - | + - | - + + - | - + | - + + - - + | | - + + - | - + | - +
| | + - - + | | | | + - | + - | | | + - - + | | | | + - - + | | | | + - - + | | | | + - - + | | | - + | - + | | | | + - - + | |
| + - | | - + | | + - | | | + - | + - | | - + | | + - | | - + | | + - | | - + | | + - | | - + | - + | | | - + | | + - | | - + |
+ - - + + - - + + - - + + - | | + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + | | - + + - - + + - - + + - - +
+ - - + + - - + + - - + + - | + - | - + + - - + + - - + + - - + + - - + + - - + + - - + + - | - + | - + + - - + + - - + + - - +
| + - | | - + | | + - | | | + - - + | | | - + | | + - | | - + | | + - | | - + | | + - | | | + - - + | | | - + | | + - | | - + |
| | + - - + | | | | + - | + - | | - + | - + | | | | + - - + | | | | + - - + | | | | + - | + - | | - + | - + | | | | + - - + | |
+ - | + - | - + + - | | + - - + + - - + | | - + + - | - + | - + + - | + - | - + + - | | + - - + + - - + | | - + + - | - + | - +
+ - | | + - - + + - | + - | - + + - | - + | - + + - - + | | - + + - | | + - - + + - | + - | - + + - | - + | - + + - - + | | - +
| | + - | + - | | | + - - + | | | | + - - + | | | - + | - + | | | | + - | + - | | | + - - + | | | | + - - + | | | - + | - + | |
| + - | | | + - | + - | | - + | | + - | | - + | - + | | | - + | | + - | | | + - | + - | | - + | | + - | | - + | - + | | | - + |
+ - - + + - | | + - - + + - - + + - - + + - - + | | - + + - - + + - - + + - | | + - - + + - - + + - - + + - - + | | - + + - - +
+ - - + + - | + - | - + + - - + + - - + + - | - + | - + + - - + + - - + + - | + - | - + + - - + + - - + + - | - + | - + + - - +
| + - | | | + - - + | | | - + | | + - | | | + - - + | | | - + | | + - | | | + - - + | | | - + | | + - | | | + - - + | | | - + |
| | + - | + - | | - + | - + | | | | + - | + - | | - + | - + | | | | + - | + - | | - + | - + | | | | + - | + - | | - + | - + | |
+ - | | + - - + + - - + | | - + + - | | + - - + + - - + | | - + + - | | + - - + + - - + | | - + + - | | + - - + + - - + | | - +
+ - | + - | - + + - | - + | - + + - | + - | - + + - | - + | - + + - | + - | - + + - | - + | - + + - | + - | - + + - | - + | - +
| | + - - + | | | | + - - + | | | | + - - + | | | | + - - + | | | | + - - + | | | | + - - + | | | | + - - + | | | | + - - + | |
| + - | | - + | | + - | | - + | | + - | | - + | | + - | | - + | | + - | | - + | | + - | | - + | | + - | | - + | | + - | | - + |
+ - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - +

Ruby Rev 1, 288
As an anonymous lambda literal. Shown in test program (the lambda literal is ->(n,a,b){...} )
g=
->(n,a,b){
$x=a-1
$y=b-1
$a=Array.new(m=2**n){"|"*m}
def t(u,v,m,r,f)
(m/=2)==1?$a[v+1-r/2%2][u,2]='-+-'[r%2,2]:0
if m>1
4.times{|i|i==r ?t(u+m/2,v+m/2,m,r,0):t(u+i%2*m,v+i/2*m,m,3-i,0)}
f>0?t(u+r%2*m,v+r/2*m,m,2*$x/m&1|$y*4/m&2,1):0
end
end
t(0,0,m,2*$x/m|$y*4/m,1)
$a[$y][$x]='O'
$a
}

n=gets.to_i
a=gets.to_i
b=gets.to_i
puts(g.call(n,a,b))

Ruby Rev 0, 330 ungolfed
Currently the only golfing I'm claiming is elimination of comments, unnecessary newlines and indents.
This is my first proper algorithm encoded in Ruby and it's been hard work. I'm sure there's at least 50 characters than can be eliminated, but I've done enough for now. There are some real horrors, for example the input. That can probably be fixed by a function or lambda instead of a program, but the inner function t that draws the trominoes still needs access to the global variables. I'll have to figure out the syntax for that.
A feature of my answer which is not present in the others, is that I initialize an array of strings with | characters. That means I only have to draw the +- or -+, which are next to each other on the same line.
m=2**gets.to_i                                         #get n and store 2**n in m
$x=gets.to_i-1                                         #get x and y, and...
$y=gets.to_i-1                                         #convert from 1-indexed to 0-indexed
$a=Array.new(m){"|"*m}                                 #array of m strings length m, initialized with "|"

def t(u,v,m,r,f)                                       #u,v=top left of current field. r=0..3= quadrant containing O. f=flag to continue surrounding O
  m/=2
  if m==1 then $a[v+1-r/2%2][u,2] ='-+-'[r%2,2];end    #if we are at char level, insert -+ or +- (array already initialized with |'s)
  if m>1 then                                          #at higher level, 4 recursive calls to draw trominoes of next size down
    4.times{|i| i==r ? t(u+m/2,v+m/2,m,r,0):t(u+i%2*m,v+i/2*m,m,3-i,0)}
    f>0?t(u+r%2*m,v+r/2*m,m,2*$x/m&1|$y*4/m&2,1):0     #then one more call to fill in the empty quadrant (this time f=1)
  end
end

$a[$y][$x]='O'                                         #fill in O
t(0,0,m,2*$x/m&1|$y*4/m&2,1)                           #start call. 2*x/m gives 0/1 for left/right quadrant, similarly 4*y/m gives 0/2 for top/bottom

puts $a                                                #dump array to stdout, elements separated by newlines.

Haskell, 170 bytes
r=reverse
g n s x y|n<1=[s]|x>k=r<$>g n s(2^n+1-x)y|y>k=r$g n s x$2^n+1-y|0<1=zipWith(++)(h s x y++h"-"k 1)$h"|"1 k++h"+"1 1 where m=n-1;k=2^m;h=g m
f n x=unlines.g n"O"x

Run online at Ideone
Example run:
*Main> putStr(f 3 3 6)
+--++--+
|+-||-+|
||+--+||
+-|-+|-+
+--+||-+
||O|-+||
|+-||-+|
+--++--+

source: Stack Exchange

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

sort: votes


text:
Stringing a Pearl Necklace
Overview
Pearls (or Masyu) is a logic game played on a grid. There are black and white pearls placed on the grid. The object is to form a single, closed loop that travels through each pearl using only straight line segments and right angles.
There are some rules that govern how the loop interacts with pearls:

White pearls must be traveled straight through, but the loop must turn in the previous and/or next cell in its path.
Black pearls must be turned upon, but the loop must travel straight through the next and previous cells in its path.
The loop must not cross or otherwise intersect itself. All cells have exactly zero or two loop entry/exits.

An example puzzle from Wikipedia (and its solution):

Your objective is to solve a given puzzle. If there are multiple possible solutions, it does not matter which one you give.
Input
Input will be an unsolved square grid. The example shown above would look like this:
..w.w.....
....w...b.
..b.b.w...
...w..w...
b....w...w
..w....w..
..b...w...
w...b....w
......ww..
..b......b

w is a white pearl, b is a black pearl, and . is an empty cell.
Assume input is valid. This means it is well formed, and at least one solution is possible. All valid puzzles are at least 3x3, and contain at least one pearl.
Output
Output is a string of coordinates representing the path. The upper left corner of the grid is 0 0, upper right is n-1 0, where n is the width of the grid.
A path is simply a series of ordered coordinates:
x1 y1 x2 y2 x3 y3 ...

The path is assumed to be closed, so you do not need to repeat the first coordinate at the end, but there is no penalty for doing so.
The output should consist of at least all corners in the path. You do not have to output every cell on the path if there is no turn. For instance, the output for the example could start with:
1 0 5 0 5 1 ...

or
1 0 2 0 3 0 4 0 5 0 5 1 ...

Output should not contain any cell not in the path. You may start at any cell in the path.

Snippet
Here's a snippet you can use to visualize your solution. Just paste in the grid you're working on and the path you output. I'm aware that it's painful to look at my code, so I just suggest you don't ;)

function draw(){document.getElementById("output").innerHTML=gridSVG+pathSVG}function drawCoords(){coords=document.getElementById("coords").value;var e=prefix+'<path fill="none" d="';if(nums=coords.match(/[^\s]+/g),!(nums.length<2)){for(e+="M "+(nums[0]*scale+offset)+" "+(nums[1]*scale+offset),i=2;i<nums.length;i+=2)e+=" L "+(nums[i]*scale+offset)+" "+(nums[i+1]*scale+offset);e+=" L "+(nums[0]*scale+offset)+" "+(nums[1]*scale+offset),e+='" stroke="black" stroke-width="2"/>'+suffix,pathSVG=e,draw()}}function drawPath(){path=document.getElementById("path").value;var e=prefix+'<path fill="none" d="'+path+'" stroke="black" stroke-width="2"/>'+suffix;pathSVG=e,draw()}function drawGrid(){grid=document.getElementById("grid").value;var e=prefix;for(lines=grid.match(/[^\s]+/g),width=lines[0].length*scale,height=lines.length*scale,i=0;i<=lines.length;i++)e+='<path stroke="gray" d="M 0 '+i*scale+" L "+width+" "+i*scale+'"/>',e+='<path stroke="gray" d="M '+i*scale+" 0 L "+i*scale+" "+height+'"/>';for(j=0;j<lines.length;j++)for(line=lines[j],i=0;i<line.length;i++)"w"==line.charAt(i)&&(e+='<circle cx="'+(i*scale+offset)+'" cy="'+(j*scale+offset)+'" r="'+.8*offset+'" stroke="black" fill="white"/>'),"b"==line.charAt(i)&&(e+='<circle cx="'+(i*scale+offset)+'" cy="'+(j*scale+offset)+'" r="'+.8*offset+'" stroke="black" fill="black"/>');e+=suffix,gridSVG=e,draw()}var prefix='<svg height="400" width="400">',suffix="</svg>",scale=30,offset=scale/2,pathSVG="",gridSVG="";
svg{position: absolute;left: 50px;}
Paste grid input here
<input id="grid" type="textarea" size="80" oninput='drawGrid()' />

Paste path output here
<input id="coords" type="textarea" size="80" oninput='drawCoords()' />

Test Cases
These test cases show one possible output for each input (except the last, which is shown unsolved). There may be other valid paths, you might go CW or CCW or start at a different point, etc. Solutions should be able to solve the test cases in seconds/minutes/hours, not days/weeks/eons.

...
w..
..b

0 0 1 0 2 0 2 1 2 2 1 2 0 2 0 1

.wb..b
......
..b...
w.ww..
......
b....b

0 0 2 0 2 2 4 2 4 1 3 1 3 0 5 0 5 5 3 5 3 4 4 4 4 3 1 3 1 4 2 4 2 5 0 5 0 2 1 2 1 1 0 1

.....w.b.w..
ww..b...b...
.w.....b....
...wbww..b.b
....b.......
w.w.........
..w......b.b
.....bb.....
.....b.....w
w.ww..b.....
...w......w.
b..w.....b..

You didn't put the solution for the last test case...

@mbomb007 Correct.

So there's no solution?

There is a solution. I left it open so answers would have something to show for their effort. Also, it may help to solve a puzzle or two by hand to get a feel for the rules, and that's hard to do if all the examples are pre-solved.

Is a grid 2x2 or larger grid with no Pearls considered valid (second sentence suggests not, and the point about the input being unsolved (if there are no unstrung pearls, it must be solved))? If so, would you expect a loop, just with no pearls in it, or what exactly? Presumably there is no requirement for any of a particular color to be present?

@VisualMelon A valid puzzle is 3x3 or larger with at least one pearl, no color requirement. Edited post.

Can I assume a limit on the maximum puzzle size or make it a compile time variable? In reality a brute force solution will work in reasonable time only up to a certain size and I haven't seen puzzles of this type bigger than 30 in one dimension.

@nutki The algorithm should theoretically work for any size in finite time, assuming infinite resources. However, it only needs to work in reasonable time for the test cases given. The time limit is really only to discourage the brutest of brute forces (something like 2^(n^2)), to facilitate testing.

Oh, and for anyone who likes this type of puzzle, there's this: http://manpages.ubuntu.com/manpages/precise/man6/pearl.6.html

@Geobits, is then compile time variable fine? This is what my solution currently does. If that is not OK, then C is penalized as then you require dynamic memory allocation and in C I need to use libc for that plus I cannot use 2D arrays which need to be statically sized. On the other hand I can easily set the limit to 1000x1000 and for that size the code wouldn't finish in this universe.

@nutki Yes, that's fine. At most, just add a short note saying that the byte size would be (slightly) affected if you were doing something orders of magnitude larger for some reason.

C, 590 640 760 880 963 1018
Brute force is quite fast for this. The 12x12 test runs under 10ms. Knowing that could opt for some language more appropriate for golfing.
I don't assume the board is square as the larger puzzles tend not to be square.
The W define sets the limit on the board dimensions. The actual limit is smaller W - 2 as I use extra rows for borders to avoid boundary checks.
#define W 40
int Y,X,T,P,Q[W*W],D[]={-W,-1,1,W};char B[W*W],K[W*W],I[W];
t(x,d,s){for(P=0;B[x];x*=x!=*Q)s-=K[Q[P++]=x]-1,
d=(54202126527627840ll>>2*(d*7+B[x+=D[d]]%8))&3;return x?0:s;}
m(x){int c=K[x],u=B[x-W],U=u&7,l=B[x-1],L=l&7,r=0,
i=U!=3&U!=4&L!=2&L!=4,o=(39>>U)&1?57:70;o&=(52>>L)&1?42:85;
if(x/W>Y+1){for(;P--;)printf("%d %d ",Q[P]%W-1,Q[P]/W-1);exit(0);}
if(u>7)o&=U>4?~64:~6;if(l>7)o&=L>4?~32:~10;
for(o&=c?c>1?c>2?(r=8*i,96):(r=8,i*30):~0:1;o;r++,o/=2)
if(o&1)if(B[x]=r,r%8!=1||!t(x,0,T))m(x+1);B[x]=0;}
main(){for(;gets(I);Y++)for(X=0;I[X];X++)
T+=(K[X+1+Y*W+W]=I[X]/36)-1;m(W);}

Test me.
Here is a more challenging test case:
.b.....b.b.......b..
.....w.....b.w....w.
....w.........w.....
..bb.....w.w.b....b.
.w.....b..b......w..
.....b..............
.b..........b.b..bw.
....w....w....b...w.
.......bb...b...w...
..b.......w.........
....b.w.....w.b...b.
w...b...w..b.w.w....
b.w....w............
...b.w......b..b...b
w......w.b.ww.......
.b....b..........b..
....b....w.bb.w...w.
w..b......w...b.....
b.....w.........w...
...b....w..w..b...w.
...................b
.b..w..bb.b..b..w...
........w......b....
b....w......b..b.b..
...b..bb.w.w........
...b.......w......w.
w...w.b.w.....b....b
............w..ww...
..b.b..b....b.......
....b.........w...b.
.ww.......b.w.w.....
b.....w..w.w...b....
....ww..b.b.w....w.w
.............bb..w..
.b....w.b.b........w
....bw..........b...

I was lucky my code finds the solution quite early in the run (<5min), but the full search takes much longer (67min).

s/Brute force is quite fast/C is quite fast/

Python - 1669
Still pretty long, but fast enough to run the last example in under a second on my computer. It's probably possible to make shorter at the cost of speed, but for now it is pretty much equivalent to the ungolfed code.
Example output for last test case:
0 11 1 11 2 11 3 11 4 11 4 10 3 10 2 10 1 10 1 9 2 9 3 9 4 9 4 8 3 8 3 7 4 7 5 7 5 6 5 5 6 5 6 6 6 7 7 7 8 7 8 8 7 8 6 8 5 8 5 9 5 10 5 11 6 11 6 10 6 9 7 9 8 9 8 10 7 10 7 11 8 11 9 11 9 10 9 9 10 9 10 10 10 11 11 11 11 10 11 9 11 8 11 7 10 7 10 8 9 8 9 7 9 6 10 6 11 6 11 5 11 4 11 3 10 3 9 3 9 4 9 5 8 5 8 4 8 3 8 2 8 1 9 1 10 1 10 0 9 0 8 0 7 0 7 1 7 2 6 2 5 2 5 1 6 1 6 0 5 0 4 0 3 0 2 0 2 1 3 1 4 1 4 2 4 3 5 3 6 3 7 3 7 4 6 4 5 4 4 4 4 5 4 6 3 6 3 5 3 4 3 3 3 2 2 2 2 3 1 3 1 2 1 1 1 0 0 0 0 1 0 2 0 3 0 4 0 5 0 6 1 6 1 5 1 4 2 4 2 5 2 6 2 7 1 7 1 8 0 8 0 9 0 10

Code:
I=raw_input().split('\n');X=len(I[0]);Y=len(I);R=range
def S(g=0,c=0,x=0,y=0):
    if y>=Y:return 0
    if g==0:g=[[-1]*X for i in R(Y)];c=[[-1]*X for i in R(Y)]
    o={'.':set(R(7)),'w':{1,2},'b':{3,4,5,6}}[I[y][x]].copy()
    o&={0,1,3,4}if y<1 or g[y-1][x]in[0,1,5,6]else{2,5,6}
    o&={0,2,4,5}if x<1 or g[y][x-1]in[0,2,3,6]else{1,3,6}
    if y>Y-2:o&={0,1,5,6}
    if x>X-2:o&={0,2,3,6}
    if y>0 and g[y-1][x]in[2,3,4]:
        if'b'==I[y][x]and g[y-1][x]!=2:return 0
        if'b'==I[y-1][x]:o&={2}
        elif'w'==I[y-1][x]and g[y-2][x]==2:o&={5,6}
    if x>0 and g[y][x-1]in[1,4,5]:
        if'b'==I[y][x]and g[y][x-1]!=1:return 0
        if'b'==I[y][x-1]:o&={1}
        elif'w'==I[y][x-1]and g[y][x-2]==1:o&={3,6}
    h=[r[:]for r in c]
    if y>0 and g[y-1][x]in[2,3,4]:
        if x>0 and g[y][x-1]in[1,4,5]:
            if c[y-1][x]==c[y][x-1]:
                if(6 not in o)+any(any(i!=c[y-1][x]and i!=-1 for i in r)for r in c)+any(I[v][u]!='.'and(v>y)+(u>x)for v in R(y,Y)for u in R(X)):return 0
                g[y][x]=6
                for v in R(y,Y):
                    for u in R(X):
                        if v!=y or u>x:g[v][u]=0
                for y in R(Y):
                    for x in R(X):
                        if g[y][x]>0:break
                f=[];d=-1;u,v=p,q=x,y
                while(u,v)!=(p,q)or-1==d:f+=[u,v];d=([0,{0,2},{1,3},{2,3},{0,3},{0,1},{1,2}][g[v][u]]-{(d+2)%4}).pop();i,j={0:(u+1,v),1:(u,v-1),2:(u-1,v),3:(u,v+1)}[d];u,v=i,j
                return f
            else:
                for v in R(y+1):
                    for u in R(X):
                        if h[v][u]==c[y][x-1]:h[v][u]=c[y-1][x]
                h[y][x]=c[y-1][x]
        else:h[y][x]=c[y-1][x]
    elif x>0 and g[y][x-1]in[1,4,5]:h[y][x]=c[y][x-1]
    else:h[y][x]=max(max(r)for r in c)+1
    for n in sorted(list(o))[::-1]:
        if n==0:h[y][x]=-1
        if x>X-2:i,j=0,y+1
        else:i,j=x+1,y
        g[y][x]=n;r=S(g,h,i,j)
        if r!=0:return r
    return 0
for i in S():print i,

Ungolfed:
class Grid:
    def __init__(self,input):
        self.input = input.split('\n')
        self.x = len(self.input[0])
        self.y = len(self.input)
        self.options = {'.':{0,1,2,3,4,5,6},'w':{1,2},'b':{3,4,5,6}}

    def convert(self,grid):
        directions = [None,{0,2},{1,3},{2,3},{0,3},{0,1},{1,2}]

        for y in range(self.y):
            for x in range(self.x):
                if grid[y][x] != 0:
                    break

        chain = []
        start_pos = (x,y)
        dir = -1
        pos = start_pos
        while dir == -1 or pos != start_pos:
            chain.extend(pos)
            x,y = pos
            next_dir = (directions[grid[y][x]]-{(dir+2)%4}).pop()
            if next_dir == 0: nx,ny = x+1,y
            elif next_dir == 1: nx,ny = x,y-1
            elif next_dir == 2: nx,ny = x-1,y
            elif next_dir == 3: nx,ny = x,y+1
            dir = next_dir
            pos = (nx,ny)

        return chain

    def solve(self,grid=None,chain_ids=None,pos=(0,0)):
        x,y = pos
        if y >= self.y:
            return None

        if grid is None:
            grid = [[-1]*self.x for i in range(self.y)]
        if chain_ids is None:
            chain_ids = [[-1]*self.x for i in range(self.y)]

        options = self.options[self.input[y][x]].copy()
        if y == 0 or grid[y-1][x] in [0,1,5,6]:
            options &= {0,1,3,4}
        else:
            options &= {2,5,6}
        if y == self.y-1:
            options &= {0,1,5,6}

        if x == 0 or grid[y][x-1] in [0,2,3,6]:
            options &= {0,2,4,5}
        else:
            options &= {1,3,6}
        if x == self.x-1:
            options &= {0,2,3,6}

        if y != 0 and grid[y-1][x] in [2,3,4]:
            if self.input[y][x] == 'b' and grid[y-1][x] != 2:
                return None
            if self.input[y-1][x] == 'b':
                options &= {2}
            elif self.input[y-1][x] == 'w':
                if grid[y-2][x] == 2:
                    options &= {5,6}
        if x != 0 and grid[y][x-1] in [1,4,5]:
            if self.input[y][x] == 'b' and grid[y][x-1] != 1:
                return None
            if self.input[y][x-1] == 'b':
                options &= {1}
            elif self.input[y][x-1] == 'w':
                if grid[y][x-2] == 1:
                    options &= {3,6}

        new_chain_ids = [[i for i in row] for row in chain_ids]
        if y != 0 and grid[y-1][x] in [2,3,4]:
            if x != 0 and grid[y][x-1] in [1,4,5]:

                if chain_ids[y-1][x] == chain_ids[y][x-1]:
                    if 6 not in options:
                        return None

                    if any(any(i != chain_ids[y-1][x] and i != -1 for i in row) for row in chain_ids) or \
                    any(self.input[v][u] != '.' and (v!=y or u>x) for v in range(y,self.y) for u in range(self.x)):
                        return None

                    grid[y][x] = 6
                    for v in range(y,self.y):
                        for u in range(self.x):
                            if v != y or u > x:
                                grid[v][u] = 0

                    return self.convert(grid)

                else:
                    for v in range(y+1):
                        for u in range(self.x):
                            if new_chain_ids[v][u] == chain_ids[y][x-1]:
                                new_chain_ids[v][u] = chain_ids[y-1][x]
                    new_chain_ids[y][x] = chain_ids[y-1][x]

            else:
                new_chain_ids[y][x] = chain_ids[y-1][x]
        elif x != 0 and grid[y][x-1] in [1,4,5]:
            new_chain_ids[y][x] = chain_ids[y][x-1]
        else:
            new_chain_ids[y][x] = max(max(row) for row in chain_ids)+1

        for n in sorted(list(options),key=lambda n: -n):
            grid[y][x] = n
            if n == 0:
                new_chain_ids[y][x] = -1

            if x == self.x-1:
                nx,ny = 0,y+1
            else:
                nx,ny = x+1,y

            result = self.solve(grid,new_chain_ids,(nx,ny))
            if result is not None:
                return result

input = """

.....w.b.w..
ww..b...b...
.w.....b....
...wbww..b.b
....b.......
w.w.........
..w......b.b
.....bb.....
.....b.....w
w.ww..b.....
...w......w.
b..w.....b..

""".strip()

def print_grid(grid):
    for y,row in enumerate(grid):
        s = ""
        for i in row:
            s += {-1:'xxx',0:'   ',1:'   ',2:' | ',3:'   ',4:'   ',5:' | ',6:' | '}[i]
        s += '\n'
        for x,i in enumerate(row):
            s += {-1:'x%sx',0:' %s ',1:'-%s-',2:' %s ',3:'-%s ',4:' %s-',5:' %s-',6:'-%s '}[i] % input.split('\n')[y][x]
        s += '\n'
        for i in row:
            s += {-1:'xxx',0:'   ',1:'   ',2:' | ',3:' | ',4:' | ',5:'   ',6:'   '}[i]
        s += '\n'
        print s

result = Grid(input).solve()
print result

@Geobits Oh it seems I didn't read the rules carefully enough. Updated answer with what I believe is correct now

The new path looks good to me! +1

Lua, 830 810 765 752 739 729 710
Runs board1 and board2 just fine, but takes a while on board3.
It could save 9 bytes by outputting every path instead of just the first...
b={}s={0,0,0}R=table.insert Z=unpack for l in io.lines()do w=#l for i=1,w do
c=({b=1,w=2,['.']=3})[l:sub(i,i)]R(b,c)s[c]=s[c]+1 end end h=#b/w for e=0,w*h-1
do function g(p,d,X,t)local function G(I,r)T={Z(t)}a=b[I+1]T[a]=T[a]+1
P={Z(p)}D={Z(d)}R(P,I%w)R(P,I/w-I/w%1)R(D,r)l=#D for U=2,#p,2 do if
I==p[U-1]+w*p[U]then return end end if I==e then if T[1]==s[1]and T[2]==s[2]then
for k=1,l do K=D[k]M=D[(k-2)%l+1]N=D[k%l+1]O=D[(k+1)%l+1]if({K==N or K~=M or
N~=O,K~=N or(K==M and N==O)})[b[1+P[2*k-1]+w*P[2*k]]]then return end end
os.exit(print(table.concat(P,' ')))end else g(P,D,I,T)end end _=X%w<w-1 and
G(X+1,1)_=X/w-X/w%1<h-1 and G(X+w,2)_=X%w>0 and G(X-1,3)_=X/w-X/w%1>0 and
G(X-w,4)end g({},{},e,{0,0,0})end

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