text:
An A , or An An?
In English, there is the fun and simple difference between an and a: you use an when preceding a word starting with a vowel sound, and a when the word starts with a consonant sound.
For the sake of simplicity in this challenge, an precedes a word that starts with a vowel (aeiou), and a precedes a word that starts with a consonant.
Input
A string comprising only printable ASCII characters, with [?] appearing in places where you must choose to insert an or a. [?] will always appear before a word. You can assume that the sentence will be grammatically correct and formatted like normal.
Output
The input string with [?] replaced with the appropriate word (an or a). You do have to worry about capitalization!
When to Capitalize
Capitalize a word if it is preceded by no characters (is the first one in the input) or if it is preceded by one of .?! followed by a space.
Examples
Input: Hello, this is [?] world!
Output: Hello, this is a world!

Input: How about we build [?] big building. It will have [?] orange banana hanging out of [?] window.
Output: How about we build a big building. It will have an orange banana hanging out of a window.

Input: [?] giant en le sky.
Output: A giant en le sky.

Input: [?] yarn ball? [?] big one!
Output: A yarn ball? A big one!

Input: [?] hour ago I met [?] European.
Output: A hour ago I met an European.

Input: Hey sir [Richard], how 'bout [?] cat?
Output: Hey sir [Richard], how 'bout a cat?

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

OK thanks. Can we assume no inputs will have extra spaces between the  [?] and the word?

@DJMcMayhem, you can assume that the sentences will be grammatically correct

@Dopapp I pronounce historian as historian, but I was taught to say it  as an historian. (Pronounced as an istorian) It is hotly debated though: http://www.google.com/search?q="an+historian"

Does a/an have to be capitalized in the middle of the input when it comes at the beginning of a sentence? ("This is [?] test. [?] test.") If so, what punctuation can a sentence end with? What about sentences in quotation marks or parentheses? Or abbreviations that end in a period ("E.g. [?] input like this")? Capitalization rules have lots of weird special cases, so please be very explicit about what our programs do or don't need to handle.

Could you please clarify when to capitalize? The first character?

You should add the test case [?] hour ago I met [?] European. just to make everyone cringe.

@DLosc, I have made an edit to specify when to capitalize. Is it clear now?

What about [?]other example? 2, I guess we can expect that [?] is not at the end of the text or a sentence.

@Titus 1. There won't be anything like that. 2. Correct

@DJMcMayhem, I edited it. Is it clearer when to capitalize?

@MartinEnder You are so evil... that is soooo wrong...

Now we must have [?] hour ago I met [?] horse.

@Dopapp Yes, that's much clearer. Now it just needs a couple test cases with sentence-initial [?] after multiple different punctuation characters.

@DLosc see the last test case

What about “An honest” or “A unicorn”? English is great.

V, 41 bytes
ÍãÛ?Ý ¨[aeiou]©/an
ÍÛ?Ý/a
Í^aü[.!?] a/A

Try it online!, which conveniently can also be used to verify all test cases with no extra byte count.
This takes advantage of V's "Regex Compression". It uses a lot of unprintable characters, so here is a hexdump:
0000000: cde3 db3f dd85 20a8 5b61 6569 6f75 5da9  ...?.. .[aeiou].
0000010: 2f61 6e0a cddb 3fdd 2f61 0acd 5e61 fc5b  /an...?./a..^a.[
0000020: 2e21 3f5d 2093 612f 41                   .!?] .a/A

Unfortunately, OP said "You do have to worry about capitalization!" (emphasis mine).

@El'endiaStarman Oh I misread that. I can fix it, but I have no clue what to capitalize, since OP didn't specify.

@El'endiaStarman Fixed now.

Ruby, 78 72 bytes
->s{s.gsub(/(^|\. )?\K\[\?\]( [aeiou])?/i){"anAn"[$1?2:0,$2?2:1]+"#$2"}}

Saved 6 bytes thanks to @Jordan

Ungolfed
def f(s)
    s.gsub(/(^|\. )?\[\?\]( [aeiou])?/i) do |m|
        capitalize = $1
        vowel = $2
        replacement = if vowel then
            capitalize ? "An" : "an"
        else
            capitalize ? "A" : "a"
        end
        m.sub('[?]', replacement)
    end
end

"anAn"[...] is really clever.  You can save a few bytes by skipping the inner sub: s.gsub(/(^|\. )?\K\[\?\] ([aeiou])?/i){"anAn"[$1?2:0,$2?2:1]+" #$2"}

Perl, 48 bytes
Saved 1 byte due to Ton Hospel.
#!perl -p
s;\[\?];A.n x$'=~/^ [aeiou]/i^$"x/[^.?!] \G/;eg

Counting the shebang as one, input is taken from stdin.
Explanation
#!perl -p               # for each line of input, set $_, auto-print result

s;                      # begin regex substitution, with delimiter ;
\[\?]                   # match [?] literally, and replace with:
;
A.n x$'=~/^ [aeiou]/i   # 'A', concatenate with 'n' if post-match ($')
                        #   matches space followed by a vowel
^$"x/[^.?!] \G/         # if the match is preceded by /[^.?!] /, xor with a space
                        #   this will change An -> an

;eg                     # regex options eval, global

Sample Usage
$ echo Hello, this is [?] world! | perl a-an.pl
Hello, this is a world!

$ echo How about we build [?] big building. It will have [?] orange banana hanging out of [?] window. | perl a-an.pl
How about we build a big building. It will have an orange banana hanging out of a window.

$ echo [?] giant en le sky. [?] yarn ball? | perl a-an.pl
A giant en le sky. A yarn ball?

$ echo [?] hour ago I met [?] European. | perl a-an.pl
A hour ago I met an European.

Could you explain this, please?

Support for capitalization after /[.?!]/ followed by space is missing

@TonHospel 10 hours ago, the problem made no mention of this.

Ok, changing the spec on the fly is so unfair. PS: I love using \G to go backwarsds. PPS, a bit shorter: s;\[\?];A.n x$'=~/^ [aeiou]/^$"x/[^.?!] \G/;eg

@sudee updated to include explanation.

PHP, 207 bytes
foreach(explode("[?]",$s)as$i=>$b){$r=Aa[$k=0|!strstr(".!?",''==($c=trim($a))?".":$c[strlen($c)-1])].n[!preg_match("#^['\"´`\s]*([aeiou]|$)#i",$d=trim($b))];echo$i?$r.$b:$b;$a=$i?''==$d?a:$b:(''==$d?".":a);}

I like solutions more complete from time to time ...
but I must admit that this is a little overkill, although it´s not at all finished.
Save to file, run with php <filename> with input from STDIN.
test cases
How about we build [?] big building ... with [?] orange banana hanging out of [?] window.
=>  How about we build a big building ... with an orange banana hanging out of a window.

Hello, this is [?] world!               =>  Hello, this is a world!
Should I use [?] '[?]' or [?] '[?]'?    =>  Should I use an 'an' or an 'a'?
[?] elephant in [?] swimsuit.           =>  An elephant in a swimsuit.

How I met your moth[?].                 =>  How I met your motha.
b[?][?][?] short[?]ge!                  =>  banana shortage!

breakdown
foreach(explode("[?]",$s)as$i=>$b)
{
    $r=
        // lookbehind: uppercase if the end of a sentence precedes
        Aa[$k=0|!strstr(".!?",''==($c=trim($a))?".":$c[strlen($c)-1])]
        .
        // lookahead: append "n" if a vowel follows (consider quote characters blank)
        n[!preg_match("#^['\"´`\s]*([aeiou]|$)#i",$d=trim($b))]
    ;
    // output replacement and this part
    echo$i?$r.$b:$b;
    // prepare previous part for next iteration
    $a=$i               // this part was NOT the first:
        ?   ''==$d
            ? a             // if empty -> a word ($r from the previous iteration)
            : $b            // default: $b
        :  (''==$d      // this WAS the first part:
            ? "."           // if empty: end of a sentence (= uppercase next $r)
            : a             // else not
        )
    ;
    // golfed down to `$a=!$i^''==$d?a:($i?$b:".");`
}

Upvote for "banana shortage"! LOL

@MonkeyZeus: Try [?][?][?]s [?]lert!

All I can imagine is a heartbroken Donkey Kong worried sick about the shortage now :(

Minkolang 0.15, 75 bytes
od4&r$O."]?["30$Z3&00w4X"Aa"I2-"Aa ."40$Z,*2&$rxr$O" aeiou"od0Z1=3&"n"r5X$r

Try it here!
Explanation
od                                                                    Take character from input and duplicate (0 if input is empty)
  4&                                                                  Pop top of stack; jump 4 spaces if not 0
    r$O.                                                              Reverse stack, output whole stack as characters, and stop.

    "]?["                                                             Push "[?]" on the stack
         30$Z                                                         Pop the top 3 items and count its occurrences in the stack
              3&                                                      Pop top of stack; jump 3 spaces if not 0
                00w                                                   Wormhole to (0,0) in the code box

                3X                                                    Dump the top 3 items of stack
                  "Aa"                                                Push "aA"
                      I2-                                             Push the length of stack minus 2
                         "Aa ."40$Z,                                  Push ". aA" and count its occurrences, negating the result
                                    *                                 Multiply the top two items of the stack
                                     2&$r                             Pop top of stack and swap the top two items if 0
                                         x                            Dump top of stack
                                          r                           Reverse stack
                                           $O                         Output whole stack as characters
                                             " aeiou"                 Push a space and the vowels
                                                     od               Take a character from input and duplicate
                                                       0Z             Pop top of stack and count its occurrences in the stack (either 1 or 2)
                                                         1=           1 if equal to 1, 0 otherwise
                                                           3&         Pop top of stack; jump 3 spaces if not 0
                                                             "n"      Push "n" if top of stack is 0

                                                             r        Reverse stack
                                                              5X      Dump top five items of stack
                                                                $r    Swap top two items of stack

Note that because Minkolang is toroidal, when the program counter moves off the right edge, it reappears on the left. Certainly golfable, but because I had to add 21 bytes because of the spec, I may not try.

Am I the only one who wants to go play excitebike after reading that explanation?

JavaScript (ES6), 90  86 87 85
Edit once more as the spec for capitalization has changed (more sensible now)
Edit again 1 byte save thx @Huntro
Edit 2 more bytes to manage quotes and the like, as pointed out by IsmaelMiguel (even if I don't know if it's requested by op). Note that previously I had counted 86 bytes but they were 85
Trying to follow the capitalization rule stated in the comments event if it's incomplete (at least)
x=>x.replace(/([^!?.] )?\[\?](\W*.)/g,(a,b,c)=>(b?b+'a':'A')+(/[aeiou]/i.test(c)?'n'+c:c))

Test

f=x=>x.replace(/([^!?.] )?\[\?](\W*.)/g,(a,b,c)=>(b?b+'a':'A')+(/[aeiou]/i.test(c)?'n'+c:c))

function go() {
  var i=I.value, o=f(i)
  O.innerHTML = ''+i+'\n'+o+'\n\n'+O.innerHTML
}

go()
#I { width:80% }
<input value='How about we build [?] big building. It will have [?] orange banana hanging out of [?] window.' id=I><button onclick='go()'>GO</button>

Shouldn't [?][?] give Ana? And shouldn't [?][?] a. produce Ana a.?

@IsmaelMiguel I don't understand exactly what you mean, but anyway [?] will always appear before a word. You can assume that the sentence will be grammatically correct and formatted like normal.

Got it, but your code is giving weird results for [?] "[?]". (An "A", the quotes are irrelevant) and for [?] "A". (it works fine for [?] A.).

@IsmaelMiguel [?] "[?]" is not valid input. [?] will always appear before a word  and "[?]" is not a word.

You're right, but on the 2nd example, "A" is a word in itself, right? If so, then the output of [?] "A". is incorrect.

@IsmaelMiguel got your point

It is almost working perfectly. Testing with [?] "A". [?] 'A'. [?]. [?] A. gives An "A". An 'A'. An. [?] A., when it should be An "A". An 'A'. A. An A.. The [?]. isn't important, but the [?] A. is now broken. Notice that [?] A. on itself works fine! It just breaks on that sentence.

The escaping of second ] is not need. /(\w )?\[\?](\W*.)/g

@IsmaelMiguel: [?] will never occur at the end of a sentence.

Sentences usually end with [?] dot, [?] exclamation mark or [?] question mark.

@Titus On the input [?] "A". [?] 'A'. [?]. [?] A., the result of [?]. [?] A. is incorrect. It should be A. An A. and it returns An. [?] A.. BUT I'm only interested in the [?] A., which is wrong in that example, but works fine on it's own.

@IsmaelMiguel that input is invalid as [?] will always appear before a word. (maybe I already told you) and . is not a word

Batch, 136 bytes
@set/ps=
@for %%v in (a e i o u)do @call set s=%%s:[?] %%v=an %%v%%
@set s=%s:[?]=a%
@if %s:~0,1%==a set s=A%s:~1%
@echo %s:. a=. A%

Takes a line of input on STDIN.

Python 3.5.1, 153 147 141 124 Bytes
*s,=input().replace('[?]','*');print(*['aA'[i<1or s[i-2]in'.?!']+'n'*(s[i+2]in 'aeiouAEIOU')if c=='*' else c for i,c in enumerate(s)],sep='')

Input :
[?] apple [?] day keeps the doctor away. [?] lie.
Output :
An apple a day keeps the doctor away. A lie.
123 Bytes version - This does not handle capitalization rule.
s=list(input().replace('[?]','*'));print(*['a'+'n'*(s[i+2]in 'aeiouAEIOU')if c=='*'else c for i,c in enumerate(s)],sep='')

Try it online!

Welcome to Codegolf. You could use ; and golf it.

Thank you.I do not know how to golf. Let me find out.

m.start() for should be m.start()for, s[i+2] in 'aeiouAEIOU' should be s[i+2]in'aeiouAEIOU'. An easy -3-byte shave due to whitespace.

('an','a')[s[i+2]in'aeiouAEIOU'] is inverted, you could use 'a'+'n'*(s[i+2]in'aeiouAEIOU') to fix that and save 2 bytes. Here you can find a lot of tips to golf.

you can replace the for with a list comprehension : ['a'+'n'*(s[i+2]in'aeiouAEIOU')if s[i]=='*'else s[i]for i in range(len(s))] 3 bytes longer, but then you can drop the list() conversion, and use inside the print print(*['a'+'n'*(s[i+2]in'aeiouAEIOU')if s[i]=='*'else s[i]for i in range(len(s))],sep='') saving 4 bytes overall c:

You can save several bytes by using enumerate as well: print(*['a'+'n'*(s[i+2]in 'aeiouAEIOU')if c=='*'else c for i,c in enumerate(s)],sep='').

This community is so lovely, seeing how many people are willing to help a newcomer and provide golfing tips!

Wow enumerate() is cool. Thanks @chepner.

Unless i can be negative (which I don't think it can), i==0 or can become i<1or

@Cyoce Thanks. Totally missed that one.

Good job, even without regex! You can use 'aA' instead of ['a','A'], also try replacing T if C else F with C and T or F to save a few bytes.

@MatthewJensen Thanks! for aA trick. But wasn't able to work with the boolean one.

PHP, 100 92 bytes
<?=preg_filter(["/\[\?]\K(?= [aeiou])/i","/([.?!] |^)\K\[\?]/","/\[\?]/"],[n,A,a],$argv[1]);

It was possible to further golf the regular expressions.
Gives a notice about an undefined constant but still works.
Edit: 8 bytes saved thanks to primo

It should also be possible to get your replacement array down to [n,A,a] by using look-around assertions (\K and (?= )).

Java, 180178 bytes
My first post here, I did use a part of the Kevin Cruijssen post but and up with a different approach, he helped me to reduce a bit more so, thanks to him !
String c(String s){String x[]=s.split("\\[\\?]",2),r=x[0];return x.length>1?r+(r.matches("(.+[.!?] )|(^)$")?"A":"a")+("aeiouAEIOU".contains(""+x[1].charAt(1))?"n":"")+c(x[1]):r;}

Here it is ungolfed :
static String c(String s) {
        String x[] = s.split("\\[\\?\\]", 2), r = x[0];
        return x.length > 1 ? r + (r.matches("(.+[.!?] )|(^)$") ? "A" : "a")
                + ("aeiouAEIOU".contains("" + x[1].charAt(1)) ? "n" : "") + c(x[1]) : r;
    }

And the result
A simple explanation, I use a recursive approch to find every [?].
I couldn't find a way to use the matches with insensitive case (not sure it is possible).
178bytes : Thanks to Martin Ender !

Welcome to PPCG! I don't think you need to escape the ] in your regex.

You are right, only the opening one is enought, thanks

05AB1E, 38 36 35 bytes
2FžNžM‚NèSðì…[?]©ìDu«D®'a'nN×«::}.ª

Try it online or verify all test cases.
Explanation:
2F            # Loop 2 times:
  žN          #  Push consonants "bcdfghjklmnpqrstvwxyz"
  žM          #  Push vowels "aeiou"
    ‚         #  Pair them together into a list
     Nè       #  And use the loop-index to index into this pair
  S           #  Convert this string to a list of characters
   ðì         #  Prepend a space in front of each character
     …[?]     #  Push string "[?]
         ©    #  Store it in variable `®` (without popping)
          ì   #  And prepend it in front of each string in the list as well
  }D          #  Then duplicate the list
    u         #  Uppercase the characters in the copy
     «        #  And merge the two lists together
              #   i.e. for the vowel-iteration we'd have ["[?] a","[?] e","[?] i","[?] o",
              #    "[?] u","[?] A","[?] E","[?] I","[?] O","[?] U"]
   D          #  Duplicate it
    ®         #  Push "[?]" from variable `®`
     'a      '#  Push "a"
       'n    '#  Push "n"
         N×   #  Repeated the 0-based index amount of times (so either "" or "n")
           «  #  And append it to the "a"
    :         #  Replace all "[?]" with "an"/"a" in the duplicated list
     :        #  And then replace all values of the lists in the (implicit) input-string
 }.ª          #  After the loop: sentence-capitalize everything (which fortunately retains
              #  capitalized words in the middle of sentences, like the "European" testcase)
              # (and after the loop the result is output implicitly)

There's a little bug in it. It capitalizes each word after an "an". For example "[?] orange" becomes "an Orange". Seems to work, if you add a ] after the ::

@Dorian Woops.. I removed that } later on because I thought it would save a byte, but you're indeed right that it fails for [?] vowel cases.. Thanks for letting me know!

C#, 204 235 bytes
string n(string b){for(int i=0;i<b.Length;i++){if(b[i]=='['){var r="a";r=i==0||b[i-2]=='.'?"A":r;r=System.Text.RegularExpressions.Regex.IsMatch(b[i+4].ToString(),@"[aeiouAEIOU]")?r+"n":r;b=b.Insert(i+3,r);}}return b.Replace("[?]","");}

Ungolfed full program:
using System;

class a
{
    static void Main()
    {
        string s = Console.ReadLine();
        a c = new a();
        Console.WriteLine(c.n(s));
    }

    string n(string b)
    {
        for (int i = 0; i < b.Length; i++)
        {
            if (b[i] == '[')
            {
                var r = "a";
                r = i == 0 || b[i - 2] == '.' ? "A" : r;
                r = System.Text.RegularExpressions.Regex.IsMatch(b[i + 4].ToString(), @"[aeiouAEIOU]") ? r + "n" : r;
                b = b.Insert(i + 3, r);
            }
        }
        return b.Replace("[?]", "");
    }
}

I'm sure this could be improved, especially the Regex part, but can't think of anything right now.

does it work without the imports?

Whoops, forgot to include the regex import in the count.

The golfed code should run as-is in whatever format -- if it doesn't run without the regex import, then the regex import should go in the golfed code too

Okay, thanks.  Still ironing out exactly how to answer.  The count and answer include System.Text.RegularExpressions now.

This looks good now. :) You can also check out [meta] and the [meta-tag:faq] tag there.

Racket 451 bytes (without regex)
It is obviously a long answer but it replaces a and an with capitalization also:
(define(lc sl item)(ormap(lambda(x)(equal? item x))sl))
(define(lr l i)(list-ref l i))(define(f str)(define sl(string-split str))
(for((i(length sl))#:when(equal?(lr sl i)"[?]"))(define o(if(lc(string->list"aeiouAEIOU")
(string-ref(lr sl(add1 i))0))#t #f))(define p(if(or(= i 0)(lc(string->list".!?")
(let((pr(lr sl(sub1 i))))(string-ref pr(sub1(string-length pr))))))#t #f))
(set! sl(list-set sl i(if o(if p"An""an")(if p"A""a")))))(string-join sl))

Testing:
(f "[?] giant en le [?] sky.")
(f "[?] yarn ball?")
(f "[?] hour ago I met [?] European. ")
(f "How about we build [?] big building. It will have [?] orange banana hanging out of [?] window.")
(f "Hello, this is [?] world!")

Output:
"A giant en le a sky."
"A yarn ball?"
"A hour ago I met an European."
"How about we build a big building. It will have an orange banana hanging out of a window."
"Hello, this is a world!"

Detailed version:
(define(contains sl item)
  (ormap(lambda(x)(equal? item x))sl))

(define(lr l i)
  (list-ref l i))

(define(f str)
  (define sl(string-split str))
  (for((i(length sl))#:when(equal?(lr sl i)"[?]"))
    (define an   ; a or an
      (if(contains(string->list "aeiouAEIOU")
                  (string-ref(lr sl(add1 i))0))
         #t #f ))
    (define cap   ; capital or not
      (if(or(= i 0)(contains(string->list ".!?")
                            (let ((prev (lr sl(sub1 i)))) (string-ref prev
                                       (sub1(string-length prev))))))
         #t #f))
    (set! sl(list-set sl i (if an (if cap "An" "an" )
                                 (if cap "A" "a")))))
  (string-join sl))

Yay for Racket! See also Tips for golfing in Racket / Scheme

It is an excellent language, though not meant for golfing.

Java 7, 239 214 213 bytes
String c(String s){String x[]=s.split("\\[\\?\\]"),r="";int i=0,l=x.length-1;for(;i<l;r+=x[i]+(x[i].length()<1|x[i].matches(".+[.!?] $")?65:'a')+("aeiouAEIOU".contains(x[++i].charAt(1)+"")?"n":""));return r+x[l];}

Ungolfed & test cases:
Try it here.
class M{
  static String c(String s){
    String x[] = s.split("\\[\\?\\]"),
           r = "";
    int i = 0,
        l = x.length - 1;
    for (; i < l; r += x[i]
                     + (x[i].length() < 1 | x[i].matches(".+[.!?] $")
                        ? 65
                        : 'a')
                     + ("aeiouAEIOU".contains(x[++i].charAt(1)+"")
                        ? "n"
                        : ""));
    return r + x[l];
  }

  public static void main(String[] a){
    System.out.println(c("Hello, this is [?] world!"));
    System.out.println(c("How about we build [?] big building. It will have [?] orange banana hanging out of [?] window."));
    System.out.println(c("[?] giant en le sky."));
    System.out.println(c("[?] yarn ball? [?] big one!"));
    System.out.println(c("[?] hour ago I met [?] European. "));
    System.out.println(c("Hey sir [Richard], how 'bout [?] cat?"));
    System.out.println(c("[?] dog is barking. [?] cat is scared!"));
  }
}

Output:
Hello, this is a world!
How about we build a big building. It will have an orange banana hanging out of a window.
A giant en le sky.
A yarn ball? A big one!
A hour ago I met an European.
Hey sir [Richard], how 'bout a cat?
A dog is barking. A cat is scared!

I tried using a recursive solution, I end up with 2 bytes more then you :( need to improvement maybe .. but since I use your regex, I don't like to post it.

@AxelH Could you perhaps post it on ideone and link here? Together we might spot something to golf. ;)

Here is it https://ideone.com/z7hlVi, I did find a better approch thanisEmpty using the regex ^$. I believe I end up with 202 ;)

@AxelH Ah nice. Hmm, I count 195 bytes instead of 202? Btw, you can golf it to 180 by doing a direct return with a ternary if-else: String c(String s){String x[]=s.split("\\[\\?\\]",2),r=x[0];return x.length>1?r+(r.matches("(.+[.!?] )|(^)$")?"A":"a")+("aeiouAEIOU".contains(""+x[1].charAt(1))?"n":"")+c(x[1]):r;} So definitely shorter than my loop-answer. :)

Oh yeah, i manage to put the if bloc in one line at the end, forgot to replace it. Thanks;

C (gcc), 225 207 202 201 bytes
Thanks to ceilingcat for -24 bytes
#define P strcpy(f+d,index("!?.",i[c-2])+!c?
c;d;v(i,g,f)char*i,*g,*f;{for(d=0;i[c];c++,d++)strcmp("[?]",memcpy(g,i+c,3))?f[d]=i[c]:(index("aeiouAEIOU",i[c+4])?P"An ":"an "),d++:P"A ":"a "),d++,c+=3);}

Try it online!

J, 113 bytes
[:;:inv 3(0 2&{(((('aA'{~[)<@,'n'#~])~('.?!'e.~{:))~('AEIOUaeiou'e.~{.))&>/@[^:(<@'[?]'=])1{])\' 'cut' . '([,~,)]

Try it online!
Shame, shame!

Retina, 66 60 bytes
i`\[\?\]( ([aeiou]?)[a-z&&[^aeiou])
a$.2*n$1
(^|[.?!] )a
$1A

Try it online.
Explanation:
Do a case-insensitive search for [?]  followed by a vowel or consonant, where the optional vowel is saved in capture group 2, and the entire match in capture group 1:
i`\[\?\]( ([aeiou]?)[a-z&&[^aeiou])

Replace this with an a, followed by the length of the second group amount of n (so either 0 or 1 n), followed by the letter(s) of capture group 1:
a$.2*n$1

Then match an a at either the start of the string, or after either of .?! plus a space:
(^|[.?!] )a

And uppercase that A, without removing the other characters of capture group 1:
$1A

Java (JDK), 154 bytes
s->{String v="(?= [aeiou])",q="(?i)\\[\\?]",b="(?<=^|[?.!] )";return s.replaceAll(b+q+v,"An").replaceAll(q+v,"an").replaceAll(b+q,"A").replaceAll(q,"a");}

Try it online!
Explanation:
s->{
    String v="(?= [aeiou])",          // matches being followed by a vowel
    q="(?i)\\[\\?]",                  // matches being a [?]
    b="(?<=^|[?.!] )";                // matches being preceded by a sentence beginning
    return s.replaceAll(b+q+v,"An")   // if beginning [?] vowel, you need "An"
        .replaceAll(q+v,"an")         // if           [?] vowel, you need "an"
        .replaceAll(b+q,"A")          // if beginning [?]      , you need "A"
        .replaceAll(q,"a");}          // if           [?]      , you need "a"

Pip, 62 55 54 50 bytes
Takes the string as a command-line argument.
aR-`([^.?!] )?\[\?]( [^aeiou])?`{[b"aA"@!b'nX!cc]}

Try it online!
Explanation:
a                                                   Cmdline argument
 R                                                  Replace...
  -`                           `                    The following regex (case-insensitive):
    ([^.?!] )?                                      Group 1: not end-of-sentence (nil if it doesn't match)
              \[\?]                                 [?]
                   ( [^aeiou])?                     Group 2: not vowel (nil if there is a vowel)
                                {                }  ... with this callback function (b = grp1, c = grp2):
                                 [              ]   List (concatenated when cast to string) of:
                                  b                 Group 1
                                   "aA"@!b          "a" if group 1 matched, else "A"
                                          'nX!c     "n" if group 2 didn't match, else ""
                                               c    Group 2

Perl 6, 78 bytes
{S:i:g/(^|<[.?!]>' ')?'[?] '(<[aeiou]>?)/{$0 xx?$0}{[?$0]}{'n'x?~$1} $1/}

Explanation:
{
  S
    :ignorecase
    :global
  /
    ( # $0
    | ^             # beginning of line
    | <[.?!]> ' '   # or one of [.?!] followed by a space
    ) ?             # optionally ( $0 will be Nil if it doesn't match )

    '[?] '          # the thing to replace ( with trailing space )

    ( # $1
      <[aeiou]> ?   # optional vowel ( $1 will be '' if it doesn't match )
    )

  /{
    $0 xx ?$0      # list repeat $0 if $0
                   # ( so that it doesn't produce an error )
  }{
    [ ?$0 ] # 'A' if $0 exists, otherwise 'a'
  }{
    'n' x ?~$1     # 'n' if $1 isn't empty
                   # ｢~｣ turns the Match into a Str
                   # ｢?｣ turns that Str into a Bool
                   # ｢x｣ string repeat the left side by the amount of the right

  # a space and the vowel we may have borrowed
  } $1/
}

Test:
#! /usr/bin/env perl6
use v6.c;
use Test;

my &code = {S:i:g/(^|<[.?!]>' ')?'[?] '(<[aeiou]>?)/{[?$0]~('n'x?~$1)} $1/}

my @tests = (
  'Hello, this is [?] world!'
  => 'Hello, this is a world!',

  'How about we build [?] big building. It will have [?] orange banana hanging out of [?] window.'
  => 'How about we build a big building. It will have an orange banana hanging out of a window.',

  '[?] giant en le sky.'
  => 'A giant en le sky.',

  '[?] yarn ball?'
  => 'A yarn ball?',

  '[?] hour ago I met [?] European.'
  => 'A hour ago I met an European.',

  "Hey sir [Richard], how 'bout [?] cat?"
  => "Hey sir [Richard], how 'bout a cat?",
);

plan +@tests;

for @tests -> $_ ( :key($input), :value($expected) ) {
  is code($input), $expected, $input.perl;
}

1..6
ok 1 - "Hello, this is a world!"
ok 2 - "How about we build a big building. It will have an orange banana hanging out of a window."
ok 3 - "A giant en le sky."
ok 4 - "A yarn ball?"
ok 5 - "A hour ago I met an European."
ok 6 - "Hey sir [Richard], how 'bout a cat?"

Can you remove a space from } $1 at the end (making it }$1)?

@Cyoce There is a way of doing that, but it adds more complexity elsewhere. {S:i:g/(^|<[.?!]>' ')?'[?]'(' '<[aeiou]>?)/{[?$0]~('n'x?~$1.substr(1))}$1/}

Ok, I wasn't sure how perl would parse that

Lua, 131 Bytes.
function(s)return s:gsub("%[%?%](%s*.)",function(a)return"a"..(a:find("[AEIOUaeiou]")and"n"or"")..a end):gsub("^.",string.upper)end

Although lua is a terrible Language for golfing, I feel I've done pretty well.

Racket (with regex) 228 bytes
(define(r a b c)(regexp-replace* a b c))
(define(f s)
(set! s(r #rx"[a-zA-Z ]\\[\\?\\] (?=[aeiouAEIOU])"s" an "))
(set! s(r #rx"[a-zA-Z ]\\[\\?\\]"s" a"))
(set! s(r #rx"\\[\\?\\] (?=[aeiouAEIOU])"s"An "))
(r #rx"\\[\\?\\]"s"A"))

Testing:
(f "[?] giant en le [?] sky.")
(f "[?] yarn ball?")
(f "[?] apple?")
(f "[?] hour ago I met [?] European. ")
(f "How about we build [?] big building. It will have [?] orange banana hanging out of [?] window.")
(f "Hello, this is [?] world!")

Output:
"A giant en le a sky."
"A yarn ball?"
"An apple?"
"A hour ago I met an European. "
"How about we build a big building. It will have an orange banana hanging out of a window."
"Hello, this is a world!"

Groovy, 73 162 bytes
def a(s){s.replaceAll(/(?i)(?:(.)?( )?)\[\?\] (.)/){r->"${r[1]?:''}${r[2]?:''}${'.?!'.contains(r[1]?:'.')?'A':'a'}${'aAeEiIoOuU'.contains(r[3])?'n':''} ${r[3]}"}}

edit: damn, the capitalization totally complicated everything here

Does this capitalize at the beginning of a sentence?

nope.
I see now, that the challenge description has been changed in the meantime...

"Give me [?] hour with [?] open cellar door." Breaks your code: https://groovyconsole.appspot.com/edit/5159915056267264

the challenge description still is completely inconsistent. first it says "You do have to worry about capitalization!" and directly after that there are the rules for capitalization

It is consistent. You have to worry about capitalization (that is, you need to manage it). Then it explains how

yep, now i see, i was wrong. my subconsciousness must have added the "not" while reading

C# 209 bytes
string A(string b){var s=b.Split(new[]{"[?]"},0);return s.Skip(1).Aggregate(s[0],(x,y)=>x+(x==""||(x.Last()==' '&&".?!".Contains(x.Trim().Last()))?"A":"a")+("AEIOUaeiou".Contains(y.Trim().First())?"n":"")+y);}
Formatted
string A(string b)
{
    var s = b.Split(new[] { "[?]" }, 0);
    return s.Skip(1).Aggregate(s[0], (x, y) => x + (x == "" || (x.Last() == ' ' && ".?!".Contains(x.Trim().Last())) ? "A" : "a") + ("AEIOUaeiou".Contains(y.Trim().First()) ? "n" : "") + y);
}

Python 3, 104 103 bytes
-1 bytes, unescaped ]
lambda s:r('(^|[.?!] )a',r'\1A',r('a( [aeiouAEIOU])',r'an\1',r('\[\?]','a',s)));from re import sub as r

Try it online!
Starts by replacing all occurences of [?] with a,
Then replaces all a followed by a vowel, with an.
Then replaces all a at the start of input or a sentence with A.
Assumes that [?] will never be touching another word, and that lower-case a should never begin a sentence.

PowerShell, 124 bytes
inspired by Avi's answer for Java.
$args-replace(($b='(?<=^|[?.!] )')+($q='\[\?]')+($v='(?= [aeiou])')),'An'-replace"$q$v",'an'-replace"$b$q",'A'-replace$q,'a'

Try it online!


text:
Recreate the Windows ME screensaver as ASCII

This challenge is inspired from this answer at the Ask Ubuntu Stack Exchange.

Intro
Remember the Windows ME screensaver with the pipes? Time to bring the nostalgia back!

Challenge
You should write a program or function which will output an ASCII representation of the screensaver. In the screensaver there should be a single pipe which will grow in semi-random directions.
The start of the pipe will be randomly placed at any of the borders of the screen and the pipe piece should be perpendicular to the border (corner first-pipes can either be horizontal or vertical). Each tick the pipe will grow in the direction it is facing (horizontal/vertical) at an 80% chance or take a corner at a 20% chance.
Pipe representation
To create the pipe, 6 unicode characters will be used
─    \u2500    horizontal pipe
│    \u2502    vertical pipe
┌    \u250C    upper left corner pipe
┐    \u2510    upper right corner pipe
└    \u2514    lower left corner pipe
┘    \u2518    lower right corner pipe

Input
The program / function will take 3 values of input, which can be gathered through function parameters or prompted to the user.

Amount of ticks
Screen width
Screen height

Amount of ticks
For every tick, a piece of pipe will be added to the screen. Pipes will overwrite old pipe pieces if they spawn at the same position.
For example, take a screen of size 3x3
ticks == 3
─┐
 ┘

ticks == 4
─┐
└┘

ticks == 5
│┐
└┘

Whenever a pipe exits the screen, as in the last example at 5 ticks, then a new pipe will spawn at a random border. For example:
ticks == 6
│┐
└┘
  ─

The new pipe should have a 50% chance of being horizontal or vertical.
Screen width/height
The screen width and height can be combined into a single value if that's preferrable in your language of choice. The screen width and height will always have a minimum value of 1 and a maximum value of 255. If your language of choice supports a console or output screen which is smaller than a 255x255 grid of characters then you may assume that the width and height will never exceed the boundaries of your console. (Example: Windows 80x25 cmd window)
Output
The output of your program/function should be printed to the screen, or returned from a function. For every run of your program, a different set of pipes should be generated.
Test cases
The following test cases are all random examples of valid outputs
f(4, 3, 3)
 │
─┘
  │

f(5, 3, 3)
 │
─┘┌
  │

f(6, 3, 3)
─│
─┘┌
  │

f(7, 3, 3)
──
─┘┌
  │

Obviously, the more ticks that have occured, the harder it becomes to prove the validity of your program. Hence, posting a gif of your output running will be preferred. If this is not possible, please post a version of your code which includes printing the output. Obviously, this will not count towards your score.
Rules

This is code-golf, shortest amount of bytes wins
Standard loopholes apply
If you use the unicode pipe characters in your source code, you may count them as a single byte

This is quite a hard challenge that can possibly be solved in many creative ways, you are encouraged to write an answer in a more verbose language even though there are already answers in short esolangs. This will create a catalog of shortest answers per language. Bonus upvotes for fancy coloured gifs ;)
Happy golfing!
Disclaimer: I am aware that Unicode characters aren't ASCII, but in lack of a better name I just call it ASCII art. Suggestions are welcome :)

The unicode characters that you want in the output are not ASCII.

@Wheat Wizard I know, I use different terms throughout this post. However, the collection of text characters to create art can be called ASCII art (frankly, I didn't know what else to call it).. Edited in a disclaimer xD

I think this should be tagged ascii-art instead of graphical-output -- reference

Nostalgia and Windows ME don't fit well on the same line

@TimmyD you are right, updated the tags

I sort of wish this were [tag:popularity-contest] so I could go a little overboard on solving this, but I'm definitely taking a look at this this weekend. (Golf is cool too, of course!)

@CAD97 That was my initial choice but those are generally frowned upon, couldn't really think of solid winning criterium for such a challenge either, other than "make it look fancy"

The 3D Pipes screensaver predated Windows ME.

"The start of the pipe will be randomly placed at any of the borders of the screen." Must the first pipe be perpendicular to the edge of the screen?

@Jordan yes, the first pipe should always "come out of the border", the direction of corner first-pipes doesn't matter

@BassdropCumberwubwubwub Do we have any options if our language doesn't support unicode? i.e. substituting ASCII chars

@Suever You could substitute the unicodes with (any) ascii characters to demonstrate your language but it would make the answer non-competing

“Whenever a pipe exits the screen (…), then a new pipe will spawn at a random border.” In the animation you posted seems to wrap around and only the color change is random. Why not keep it like that in the rule?

"The screen width and height can be combined into a single value if that's preferrable in your language of choice." Do you mean we can use the same value for width and height, i.e. always have a square screen?

May we output infinitely, instead of a fixed amount of ticks, like a screensaver?

@Jordan I thought he meant tuples.

Obligatory reference: Ballmer Peak

JavaScript (ES6), 264 266 274 281
(t,w,h,r=n=>Math.random()*n|0,g=[...Array(h)].map(x=>Array(w).fill` `))=>((y=>{for(x=y;t--;d&1?y+=d-2:x+=d-1)x<w&y<h&&~x*~y?0:(d=r(4))&1?x=r(w,y=d&2?0:h-1):y=r(h,x=d?0:w-1),e=d,d=r(5)?d:2*r(2)-~d&3,g[y][x]="─└ ┌┐│┌  ┘─┐┘ └│"[e*4|d]})(w),g.map(x=>x.join``).join`
`)

Counting unicode drawing characters as 1 byte each. (As specified by OP)
Less golfed
(t,w,h)=>{
  r=n=>Math.random()*n|0; // integer range random function
  g=[...Array(h)].map(x=>Array(w).fill(' ')); // display grid
  for (x=y=w;t--;)
    x<w & y<h && ~x*~y||( // if passed boundary
      d = r(4), // select random direction
      d & 1? (x=r(w), y=d&2?0:h-1) : (y=r(h), x=d?0:w-1) // choose start position
    ),
    e=d, d=r(5)?d:2*r(2)-~d&3, // change direction 20% of times
    g[y][x]="─└ ┌┐│┌  ┘─┐┘ └│"[e*4|d], // use char based on current+prev direction
    d&1 ? y+=d-2 : x+=d-1 // change x,y position based on direction
  return g.map(x=>x.join``).join`\n`
}

Animated test
Note: trying to keep the animation time under 30 sec,more thicks make animation pace faster

f=(t,w,h,r=n=>Math.random()*n|0,g=[...Array(h)].map(x=>Array(w).fill` `))=>
{
  z=[]
  for(x=y=w;t--;d&1?y+=d-2:x+=d-1)
    x<w&y<h&&~x*~y?0:(d=r(4))&1?x=r(w,y=d&2?0:h-1):y=r(h,x=d?0:w-1),
    e=d,d=r(5)?d:2*r(2)-~d&3,g[y][x]="─└ ┌┐│┌  ┘─┐┘ └│"[e*4|d],
    z.push(g.map(x=>x.join``).join`\n`)
  return z
}

function go() {
  B.disabled=true
  var [t,w,h]=I.value.match(/\d+/g)
  var r=f(+t,+w,+h)
  O.style.width = w+'ch';
  var step=0
  var animate =_=>{
    S.textContent = step
    var frame= r[step++]
    if (frame) O.textContent = frame,setTimeout(animate, 30000/t);
    else   B.disabled=false
  }

  animate()
}

go()
#O { border: 1px solid #000 }
Input - ticks,width,height
<input value='600,70,10' id=I><button id=B onclick='go()'>GO</button>

Just when I thought QBasic might actually win a golf challenge. ;) Have an upvote.

Nothing says nostalgia quite like...
QBasic, 332 bytes
INPUT t,w,h
RANDOMIZE
CLS
1b=INT(RND*4)
d=b
IF b MOD 2THEN c=(b-1)/2*(w-1)+1:r=1+INT(RND*h)ELSE c=1+INT(RND*w):r=b/2*(h-1)+1
WHILE t
LOCATE r,c
m=(b+d)MOD 4
IF b=d THEN x=8.5*m ELSE x=13*m+(1<((b MOD m*3)+m)MOD 5)
?CHR$(179+x);
r=r-(d-1)MOD 2
c=c-(d-2)MOD 2
b=d
d=(4+d+INT(RND*1.25-.125))MOD 4
t=t-1
IF(r<=h)*(c<=w)*r*c=0GOTO 1
WEND

QBasic is the right language for the task because:

Its encoding includes box drawing characters--no need for Unicode
LOCATE allows you to print to any location on the screen, overwriting what was there previously
Microsoft®

Specifics
This is golfed QBasic, written and tested on QB64 with autoformatting turned off. If you type/paste it into the actual QBasic IDE, it will add a bunch of spaces and expand ? into PRINT, but it should run exactly the same.
The program inputs three comma-separated values: ticks, width, and height. It then asks for a random-number seed. (If this behavior isn't acceptable, change the second line to RANDOMIZE TIMER for +6 bytes.) Finally, it draws the pipes to the screen.
The maximum dimensions that can be entered are 80 (width) by 25 (height). Giving a height of 25 will result in the bottom row getting cut off when QBasic says "Press any key to continue."
How?
TL;DR: A lot of math.
The current row and column are r and c; the current direction is d and the previous direction is b. Direction values 0-3 are down, right, up, left. Arithmetic translates those into the correct step values for r and c, as well as the correct edge coordinates to start on.
The box drawing characters │┐└─┘┌ are code points 179, 191, 192, 196, 217, and 218 in QBasic. Those appear pretty random, but it still used fewer characters to generate the numbers with some (pretty convoluted, I'm-not-sure-even-I-understand-it) math than to do a bunch of conditional statements.
The code for changing direction generates a random number between -0.125 and 1.125 and takes its floor. This gives -1 10% of the time, 0 80% of the time, and 1 10% of the time. We then add this to the current value of d, mod 4. Adding 0 keeps the current direction; adding +/-1 makes a turn.
As for control flow, the WHILE t ... WEND is the main loop; the section before it, starting with line number 1 (1b=INT(RND*4)), restarts the pipe at a random edge. Whenever r and c are outside the window, we GOTO 1.
Show me the GIF!
Here you go:

This was generated by a somewhat ungolfed version with animation, color, and an automatic random seed:
INPUT t, w, h
RANDOMIZE TIMER
CLS

restart:
' Calculate an edge to start from

b = INT(RND * 4)
'0: top edge (moving down)
'1: left edge (moving right)
'2: bottom edge (moving up)
'3: right edge (moving left)
d = b

' Calculate column and row for a random point on that edge
IF b MOD 2 THEN
    c = (b - 1) / 2 * (w - 1) + 1
    r = 1 + INT(RND * h)
ELSE
    c = 1 + INT(RND * w)
    r = b / 2 * (h - 1) + 1
END IF
COLOR INT(RND * 15) + 1

WHILE t
    ' Mathemagic to generate the correct box-drawing character
    m = (b + d) MOD 4
    IF b = d THEN
        x = 17 * m / 2
    ELSE
        x = 13 * m + (1 < ((b MOD m * 3) + m) MOD 5)
    END IF
    LOCATE r, c
    PRINT CHR$(179 + x);

    ' Update row and column
    r = r - (d - 1) MOD 2
    c = c - (d - 2) MOD 2
    ' Generate new direction (10% turn one way, 10% turn the other way,
    ' 80% go straight)
    b = d
    d = (4 + d + INT(RND * 1.25 - .125)) MOD 4

    ' Pause
    z = TIMER
    WHILE TIMER < z + 0.01
        IF z > TIMER THEN z = z - 86400
    WEND

    t = t - 1
    IF r > h OR c > w OR r = 0 OR c = 0 THEN GOTO restart
WEND

I've typed this into my MS-DOS v6.22 VM :-)

Python 2.7, 624 616 569 548 552 bytes
from random import*
from time import*
i=randint
z=lambda a,b:dict(zip(a,b))
c={'u':z('lur',u'┐│┌'),'d':z('ldr',u'┘│└'),'l':z('uld',u'└─┌'),'r':z('urd',u'┘─┐')}
m=z('udlr',[[0,-1],[0,1],[-1,0],[1,0]])
def f(e,t,w,h):
 seed(e);s=[w*[' ',]for _ in' '*h]
 while t>0:
  _=i(0,1);x,y=((i(0,w-1),i(0,1)*(h-1)),(i(0,1)*(w-1),i(0,h-1)))[_];o=('du'[y>0],'rl'[x>0])[_]
  while t>0:
   d=c[o].keys()[i(7,16)//8];s[y][x]=c[o][d];x+=m[d][0];y+=m[d][1];t-=1;sleep(.5);print'\n'.join([''.join(k)for k in s]);o=d
   if(x*y<0)+(x>=w)+(y>=h):break

The first parameter is a seed, same seeds will generate the same output, printing each step with a 500 ms delay.

-10 bytes thanks to @TuukkaX

repl it
Example run
f(5,6,3,3)

will output

  ┐

 ─┐

──┐

┘─┐

┐
┘─┐

verbose version
import random as r
from time import *
char={
'u':{'u':'│','l':'┐','r':'┌'},
'd':{'d':'│','l':'┘','r':'└'},
'l':{'u':'└','d':'┌','l':'─'},
'r':{'u':'┘','d':'┐','r':'─'}
}
move={'u':[0,-1],'d':[0,1],'l':[-1,0],'r':[1,0]}
def f(seed,steps,w,h):
 r.seed(seed)
 screen=[[' ',]*w for _ in ' '*h]
 while steps > 0:
  if r.randint(0,1):
   x,y=r.randint(0,w-1),r.randint(0,1)*(h-1)
   origin='du'[y>0]
  else:
   x,y=r.randint(0,1)*(w-1),r.randint(0,h-1)
   origin = 'rl'[x>0]
  while steps > 0:
   direction = char[origin].keys()[r.randint(0,2)]
   screen[y][x]=char[origin][direction]
   x+=move[direction][0]
   y+=move[direction][1]
   steps-=1
   sleep(0.5)
   print '\n'.join([''.join(k) for k in screen]),''
   if x<0 or y<0 or x>=w or y>=h:
    break
   origin=direction

There's an useless whitespace at if x*y<0 or. 0.5 can be reduced to .5. import * could be import*. ''.join(k) for has an useless whitespace. You should also be able to keep dict in a variable and call it each time you use it. Haven't tested how much this saves, but by saving the dict(zip(a,b)) in a lambda that does the job for two strings (a, b), it should chop some. +1.

C (GCC/linux), 402 353 352 302 300 298 296 288 bytes
#define R rand()%
x,y,w,h,r;main(c){srand(time(0));scanf(
"%d%d",&w,&h);for(printf("\e[2J");x%~w*
(y%~h)||(c=R 8,(r=R 4)&1?x=1+R w,y=r&2
?1:h:(y=1+R h,x=r&2?1:w));usleep('??'))
printf("\e[%dm\e[%d;%dH\342\224%c\e[H\n",
30+c,y,x,2*"@J_FHAF__L@HL_JA"[r*4|(r^=R 5
?0:1|R 4)]),x+=--r%2,y+=~-r++%2;}

Credit to edc65 for storing the direction in a single 4-bit number.
Reads a width/height on stdin before looping the screensaver forever. E.g.:
gcc -w golf.c && echo "25 25" | ./a.out

Or for a full-screen screensaver:
gcc -w golf.c && resize | sed 's/[^0-9]*//g' | ./a.out

For readability I added newlines. Requires a linux machine with a terminal respecting ANSI codes. Has colors! If you remove color support it costs 17 bytes less.

Ruby, 413 403 396 bytes

A function that takes a number of ticks and a width as input and returns the final screen as a string. Could no doubt be golfed more.
->t,w{k=[-1,0,1,0,-1]
b=(" "*w+$/)*w
f=->t,a=[[0,m=rand(w),2],[w-1,m,0],[m,0,1],[m,w-1,3]].sample{n,m,i=a
d=k[i,2]
q=->n,m,i{_,g,j=rand>0.2?[[1,0],[3,0],[0,1],[2,1]].assoc(i):"021322033132243140251350".chars.map(&:to_i).each_slice(3).select{|c,|c==i}.sample
v,u=k[j||=i,2]
y=n+v
x=m+u
[g,y,x,j]}
g,y,x,j=q[n,m,i]
b[n*w+n+m]="─│┌┐┘└"[g]
y>=0&&y<w&&x>=0&&x<w ?t>1?f[t-1,[y,x,j]]:b:f[t]}
f[t]}

See it on repl.it: https://repl.it/Db5h/4
In order to see it in action, insert the following after the line that begins b[n*w+n+m]=:
puts b; sleep 0.2

...then assign the lambda to a variable e.g. pipes=->... and call it like pipes[100,20] (for 100 ticks and a 20x20 screen).
Ungolfed & explanation
# Anonymous function
# t - Number of ticks
# w - Screen width
->t,w{
  # The cardinal directions ([y,x] vectors)
  # Up = k[0..1], Right = k[1..2] etc.
  k = [-1, 0, 1, 0, -1]

  # An empty screen as a string
  b = (" " * w + $/) * w

  # Main tick function (recursive)
  # t - The number of ticks remaining
  # a - The current position and vector index; if not given is generated randomly
  f = ->t,a=[[0,m=rand(w),2], [w-1,m,0], [m,0,1], [m,w-1,3]].sample{
    # Current row, column, and vector index
    n, m, i = a
    d = k[i,2] # Get vector by index

    # Function to get the next move based on the previous position (n,m) and direction (d)
    q = ->n,m,i{
      # Choose the next pipe (`g` for glyph) and get the subsequent vector index (j)
      _, g, j = (
        rand > 0.2 ?
          [[1,0], [3,0], [0,1], [2,1]].assoc(i) : # 80% of the time go straight
          "021322033132243140251350".chars.map(&:to_i).each_slice(3)
            .select{|c,|c==i}.sample
      )

      # Next vector (`v` for vertical, `u` for horizontal)
      # If straight, `j` will be nil so previous index `i` is used
      v, u = k[j||=i, 2]

      # Calculate next position
      y = n + v
      x = m + u

      # Return next glyph, position and vector index
      [g, y, x, j]
    }

    # Get next glyph, and subsequent position and vector index
    g, y, x, j = q[n, m, i]

    # Draw the glyph
    b[n * w + n + m] = "─│┌┐┘└"[g]

    # Check for out-of-bounds
    y >= 0 && y < w && x >=0 && x < w ?
      # In bounds; check number of ticks remaining
      t > 1 ?
        f[t-1, [y,x,j]] : # Ticks remain; start next iteration
        b : # No more ticks; return final screen

      # Out of bounds; repeat tick with new random start position
      f[t]
  }
  f[t]
}

source: Stack Exchange

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

sort: votes


text:
Lord of the Golfs
Intro
In J. R. R. Tolkien's Lord of the Rings, this phrase is on the cover of each book.
Three Rings for the Elven-kings under the sky,
Seven for the Dwarf-lords in their halls of stone,
Nine for Mortal Men doomed to die,
One for the Dark Lord on his dark throne
In the Land of Mordor where the Shadows lie.
One Ring to rule them all, One Ring to find them,
One Ring to bring them all, and in the darkness bind them,
In the Land of Mordor where the Shadows lie

However, this isn't that interesting. It's just kolmogorov-complexity. Let's change this to interesting-nonconstant-output.
What you have to do
Use the Stack Exchange API (or codegolf.stackexchange.com/users, or the Stack Exchange Data Explorer) and find the two users with the highest scores in code-golf, the newest user, and highest-reputation user with only negatively scored code-golf post.
Then, you must insert these usernames into the following text:
Three Golfs for the <highest-scored code-golf user>-king under the sky,
Seven for the <second-highest-scored code-golf user>-lord in their halls of stone,
Nine for the Mortal <newest user> doomed to die,
One for the Dark Lord <highest reuptation user with only negative scored code-golf posts>
In the land of Golfdor, where the Golfers lie
One Golf to rule them all, One Golf to find them,
One Golf to bring them all, and in the darkness bind them,
In the Land of Golfdor, where the Golfers lie

You must insert the four usernames you found into the text in the angle-brackets.
Other Rules

This is code-golf so the shortest code wins.
No URL Shorteners (including ppcg.(ga|lol))

Do you want In the Land of Golfdor, where the Golfers lie in the output twice like it is on the books?

Can we assume that there will be at least one user with only negatively scored code golf posts?

@Riley I don't know what you mean. I want the text outputted the way I specify it in the question.

@MartinEnder I assume there is at least one, so you can also. If there isn't you can error.

@NoOneIsHere I just meant that the Lord of the rings text is 8 lines long and the output text is only 7. I just wanted to make sure it wasn't a typo.

@Riley Oh, I see. Editing.

Could the dark lord have 0 points in code-golf, or must it be a negative score?

@MegaTom It must be negative.

So I need to find someone who has the highest score out of all the people who have at least one code-golf post, but all of their code-golf posts are negative scoring? is that the correct interpretation?

@MegaTom Highest reputation, but only negative scored [tag:code-golf] posts.

Is this query the correct way to go about it? https://data.stackexchange.com/codegolf/query/540563/find-dark-lord (I have no clue how to make this a API call)

@MegaTom Yes. That is correct.

Let us continue this discussion in chat.

I suggest adding gfa1.tk too, even though it was made by a URL shortener.

PHP, 577 bytes
not tested; I currently have no system available with allow_url_fopen=On
and I didn´t take the time to copy&paste the page sources.
function g($s){return join(file("http://codegolf.stackexchange.com/$s"));}$m=preg_match_all;$m("#r-de.+/(\d+)/.+>(.+)<#U",$a=g($u="$u&filter=all"),$b);$h=$b[2];$m("#>(.+)$n)if($m("#st \">(-?)\d+#",$e=g("search?tab=votes&q=user:$n+[code-golf]"),$d)&&$d[1][0])break 2;if($a=strstr($a,"l=\"n"))$m("#r-de.+/(\d+)/.+>(.+)<#U",$a=g("$u&page=".$p+=!$p++),$b);}$m("#(.+)#U",g("q/93545"),$t);echo join([1=>$h[0],3=>$h[1],5=>$c[1][0],7=>$b[2][$i];]+split("#&[lg]t;#",$t[1][2]));

breakdown
// function to get page content from ppcg
function g($s){return join(file("http://codegolf.stackexchange.com/$s"));}

$m=preg_match_all;

// A,B: highest scores: find user names
$m("#r-de.+/(\d+)/.+>(.+)<#U",$a=g($u="users?filter=all"),$b);
$h=$b[2];   // remember the names

// C: new users: find username after "1 in one day"
$m("#>(.+)$n)
        // find "vote-count-post" in code-golf votes for that user
        if($m("#st \">(-?)\d+#",$e=g("search?tab=votes&q=user:$n+[code-golf]"),$d)
        &&$d[1][0])             // test if highest vote is negative
            break 2;
    // none found yet?
    if($a=strstr($a,"l=\"n"))   // if there is a "next" link, get next page
        $m("#r-de.+/(\d+)/.+>(.+)<#U",$a=g("$u&page=".$p+=!$p++),$b);
}

$m("#(.+)#U",g("q/93545"),$t); // get code blocks from question page

echo join([         // 4. join and print
    1=>$h[0],           // first two results from first preg_match
    3=>$h[1],
    5=>$c[1][0],        // first result from second preg_match
    7=>$b[2][$i];       // $i-th username from (latest) reputation list
]+                  // 3. and replace indexes 1,3,5,7 with above array
split("#&[lg]t;#",  // 2. split by "<" and ">"
    $t[1][2]        // 1. output template is the 3rd code block
));

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


text:
Round to n Sig Figs
Challenge
Given a number x and a number n, round number x to n significant figures and output the result.
Significant figures
The significant figures of a number are digits that carry meaning contributing to its measurement resolution. This includes all numbers except leading zeroes.
Bear in mind that leading zeroes after a decimal point are still insignificant figures.
When rounding a digit, you must round away from zero if the following digit is greater or equal than five.
All trailing zeroes after a decimal point are counted as significant.
Input
The first number will be x, the number to be rounded. The second number will be n, the number of significant figures you should round x to.
x will be a number (your code should handle both integers and floating points) between -1,000,000,000 and 1,000, 000,000 inclusive. n will be a positive integer between 1 and 50 inclusive. n will never be greater than the nunber of digits in x.
The input will never be 0 or any form of 0, e.g. 0.000 or 000.
Examples
Inputs: 2.6754, 2
Output: 2.7

An output of 2.7000 would be invalid because the trailing zeroes after the decimal point are counted as significant figures.

Inputs: 0.00034551, 4
Output: 0.0003455

Inputs: 50237.1238, 3
Output: 50200

Note that this must not have a decimal point.

Inputs: 2374905, 1
Output: 2000000

Inputs: 543.0489, 4
Output: 543.0

Inputs: 15, 1
Output: 20

Inputs: 520.3, 3
Output: 520

If you wish, you can output 520. instead but not 520.0.

Inputs: -53.87, 2
Output: -54

Inputs: 0.0999, 2
Output: 0.10

Rules
Built-in functions and libraries which allow you to round a number to n significant figures are disallowed.
Winning
The shortest code in bytes wins.

Yea it looks like that's right, for some reason I was remember incorrectly that leading zeros only applied to the whole number portion.

Would 2.7000 be another valid output for 2.6754, 2?

@Arnauld No, because trailing zeroes are counted as significant figures

What's the output for 2.700000000, 5? 2.7000?

@mbomb007 Yes, exactly

For Inputs: 520.3, 3, isn't the decimal point in the answer 520. crucial?

@GregMartin No, why would it?

@GregMartin I believe that it is, as that's the only thing that makes it have 3 sig figs vs. 2

@Suever I disagree, in 520.3 , the zero is significant, and although it isn't technically significant in 520, it is counted as a sig fig

@BetaDecay No it's not. The decimal point would be required for that.

@DLosc 1. Check the question body, 2. No, it isn't valid input

"200 is considered to have only ONE significant figure" - http://chemistry.bd.psu.edu/jircitano/sigfigs.html

@mbomb007, sure that may be the actual rules, but this is a simplified version of the problem, intended to be easier for programs to perform

@mbomb007 Yet 200 is necessarily ambiguous, as it's also the result of rounding 200.1 to two significant figures. I don't see a problem with allowing it to represent 1-3 sig figs versus 1-2 sig figs.

@DLosc That's why if that was the result you'd actually write it as 2.0 x 10^2, showing the 2 sigfigs.

Please add a test case for 0.0999, 2. Both of the current answers produce 0.1, but I think it should be 0.10.

@DLosc I've added it

Python 3, 83 bytes
(similar to the PHP answer)
from math import *
def s(x,n):
 y=10**(ceil(log10(abs(x)))-n)
 return y*round(x/y)

Test cases:
tests = [(2.6754,2), (0.00034551, 4), (50237.1238, 3),
        (2374905, 1), (543.0489, 4), (15, 1), (520.3, 3), (-53.87, 2)]

print ([s(x,n) for x,n in tests])

Output:
[2.7, 0.0003455, 50200, 2000000, 543.0, 20, 520, -54]

Apart from being slightly longer, another approach that I considered:
from math import *
def s(x,n):
 z=ceil(log10(abs(x)))
 return "%.*f"%(n-z,10**z*round(x/10**z,n))

... produces an incorrect output for the input of (15, 1):
['2.7', '0.0003455', '50200', '2000000', '543.0', '10', '520', '-54']

... due to floating point imprecision in the round() function. It seems likely to me that I could find test cases that would break the "round to zero decimal places" method also if I looked hard enough.
Thus, it seems to me that my solution probably isn't 100% correct for all cases and wouldn't be unless it was computed in decimal. This issue may therefore affect solutions in any language that use FP arithmetic.

Save some bytes by putting the body of s on the same line, then using semicolons. def s(x,n):y=10**(ceil(log10(abs(x)))-n);return y*round(x/y)

Also, you can remove the space in import * to make it import*

your answer for me is not ok because the rules say :"Built-in functions and libraries which allow you to round a number to n significant figures are disallowed." And you use round function with n = 0

@RosLuP: The round() function rounds to n decimal places, not to n significant figures, so it was allowed for this golf event.

PHP, 130 Bytes
<?=number_format($r=round($i=$argv[1],($n=$argv[2])-ceil(log(abs($i),10))),($d=(1+floor(log(abs($r),10))-$n))<0?abs($d):0,".","");

PHP, 133 Bytes works with values <1 for the significant figures
<?=number_format($r=round($i=$argv[1],($n=$argv[2])-floor(log(abs($i),10))-1),($d=(1+floor(log(abs($r),10))-$n))<0?abs($d):0,".","");

PHP, 56 Bytes works but skip unneccessary Zeros
<?=round($i=$argv[1],$argv[2]-floor(log(abs($i),10))-1);

Someone has stolen or deleted the round function in PHP! To make the challenge more interesting. 127 Bytes
<?=ceil($x=($i=$argv[1])*10**(($r=$argv[2])-($l=floor(log(abs($i),10))+1)))-$x<=0.5?ceil($x)*10**($l-$r):floor($x)*10**($l-$r);

It skips the unnessary Zeros too. It is a version where I use not the native round function in PHP only for joke. It belongs to the 56 Byte Version which I would prefer

Ok if not use library round ....

Batch, 660 652 bytes
@echo off
set m=%1.
set s=
if %m:~,1%==- set s=-&set m=%m:~1%
:m
if %m:~,1%==0 set m=%m:~1%&goto m
set d=%m:.=%
:d
if %d:~,1%==0 set d=%d:~1%&goto d
for /l %%i in (1,1,%2) do call set d=%%d%%0
call set r=%%d:~%2,1%%
call set d=%%d:~,%2%%
if %r% leq 4 goto r
set r=
:i
set/ai=1+%d:~-1%
set r=%i:~-1%%r%
set d=%d:~,-1%
if %i% leq 9 set d=%d%%r%&goto r
if not "%d%"=="" goto i
set d=1%r:~1%
set m=1%m%
set m=%m:1.0=.%
:r
if %m:~,2%==.0 set m=%m:.0=.%&set d=0%d%&goto r
set i=0
set p=.
:l
if %m:~,1%==. echo %s%%i%%p%%d%&exit/b
if %i%==0 set i=
if "%d%"=="" set d=0&set p=
set i=%i%%d:~,1%
set d=%d:~1%
set m=%m:~1%
goto l

Explanation: Starts by suffixing a . to the parameter in case it doesn't have one already, then trims off the sign (which is saved) and any leading zeros. The resulting variable m is saved for later because it will tell us the desired magnitude of the result. Any .s are then removed, which could result in further leading zeros, so they are removed too. n zeros are suffixed to ensure that there are enough digits to round, then the nth and first n digits are extracted. If the nth digit is not 4 or less then we tediously add 1 to the string. If the string overflows then we increase the magnitude by prefixing a 1, but if it was originally less than 0.1 we do that by removing the 1 we just added and also a 0 after the decimal point. If the magnitude is still less than 1 then we copy the zeros after the decimal point to the result, however if it is 1 or more then we extract the integer portion of the answer, adding extra zeros if necessary to reach the decimal point (which is then deleted as it would show incorrect precision). Finally the sign, integer portion, decimal point and decimal portion are concatenated.


text:
Misconstrued Monomials
There exists an equation, assuming n and x are positive,

that expresses the relationship between two monomials, one being a common misrepresentation of the other. Many people make the simple mistake of equating these (i.e. 3x^2 and (3x)^2).
Challenge
Given a positive integer, i, determine and return the solution n and x with the smallest sum as an array [n, x]. In the case of a tie, any solution set is acceptable.
Test Cases
62658722541234765
[15, 11]

202500
[4, 15]

524288
[8, 4]

33044255768277
[13, 9]

Can we return [x, n] instead of [n, x]?

Also, is there any time constraint?

n and x integers, right?

Output is in the form [n, x] and there is no time constraint @Fatalize

Yes, n and x are integers @LuisMendo

I have found 4 solutions for 2048 2048,1|32,2|2,8|1,2048 which of the 2 in the middle I should take? 524288,1|512,2|4,8|1,524288 has also 4 results

[8, 2] for 2048, as it's the pair of n and x with the smallest sum. Also [8, 4] for 524288. @JörgHülsermann

Mathematica, 61 bytes
Thanks to miles for saving 2 bytes, plus a whole bunch of bytes I counted for no reason!
Last@Select[{n,(#/n)^(1/n)}~Table~{n,2Log@#},IntegerQ@*Last]&

Computes a table of pairs {n,x}, where x = (i/n)^(1/n), using all possible values of n; keeps only those for which the corresponding x is an integer; then returns the pair with the largest value of n.
Here, "all possible values of n" ranges from 1 to 2*ln(i). This ignores the solution {n,x} = {i,1}, but that's okay since the solution {n,x} = {1,i} will suffice if it's the best choice. So x never needs to get smaller than 2, which means that n*2^n ≤ i, and all such n are less than 2*ln(i).
One can show using calculus that the pair {n,x} that minimizes their sum in this context is the same as the pair {n,x} with largest n (not counting {i,1}). That's why the initial Last is good enough to find the optimal pair.

You can compose the test condition using IntegerQ@*Last to save 2 bytes, but I also count 63 not 86 bytes in this current version.

Brachylog, 35 bytes
,[N:X]#>>==L(.rMtT;Lr.rMtT),M^:T*?,

Try it online!
Explanation
We construct a list [N, X], where N >= X, then after assigning values to it, we  try both [N, X] and [X, N] as possible output. For example, if N gets assigned to 3, we will test through backtracking [3, 1], [1, 3], [3, 2], [2, 3], [3, 3] and [3, 3]. After that the next backtracking step will occur on the value of N, which will go to 4, etc.
,[N:X]     The list [N, X]
#>         Both N and X are strictly positive
>=         N >= X
=L         Assign values to N and X, and L = [N, X]
(          Either...
    .          Output = L
    rM         M is the reverse of the Output
    tT         T is the second element of M
;          ...or...
    Lr.        Output is the reverse of L
    rM         M = L
    tT         T is the last element of M
),
M^         First element of M to the power of the second element of L (T)...
:T*?,      ... times T is equal to the Input

MATL, 22 bytes
`T@XK:"@K@-@^*G=?3Mb~.

Outputs are x, n in that order.
Input is limited by MATL's default double data type, which can accurately represent integers up to 2^53 only. This excludes the first test (still, it gives the correct result, but that can't be guaranteed in general for inputs so large).
Try it online!
Explanation
The code uses two nested loops:

The outer do...while loop goes through all possible sums n+x in increasing order. The loop will be stopped as soon as a solution is found. This guarantees that we output the solution with minimum sum.
The inner for each loop tests all n and x with that sum. When the sum coincides with the input, the inner loop is exited and the loop condition of the outer loop is set to false so that one is exited too.

Commented code:
`         % Do...while
  T       %   Push "true". Will be used as loop condition (possibly negated to exit loop)
  @       %   Push iteration index, say K, which represents n+x
  XK      %   Copy that into clipboard K
  :       %   Range [1 2 ... K]
  "       %   For each
    @     %     Push loop variable (1, 2, ... K), which represents n
    K@-   %     Compute x as K minus n
    @     %     Push n again
    ^*    %     Power, multiply. This gives n*x^n
    G=    %     Does this equal the input?
    ?     %     If so
      3M  %       Push the inputs of the third-last function, that is, x and n
      b   %       Bubble up the "true" that is at the bottom of the stack
      ~   %       Transform it into "false". This will exit the do...while loop
      .   %       Break the for loop
          %     Implicitly end if
          %   Implicitly end for
          % Implicitly end do...while
          % Implicitly display

Jelly, 23 16 bytes
×*@¥/=³
ṗ2ÇÐfSÞḢ

Given i, this generates all integer pairs with replacement in [1, i]. It then performs the same filtering and sorting as in the previous solution shown below. Since there is no time constraint, brute force will work given enough time.
Try it online!, but don't try large values online.
On my pc, it takes about 6 minutes to compute the result for i = 2048 using the inefficient version.
Efficient version
This is the previous solution for 23 bytes that is able to solve the large values quickly.
×*@¥/=³
ÆDµṚ*İ⁸żḞÇÐfSÞḢ

Given i, computes the divisors of i to generate pairs of [n, x] where n is a divisor and x = floor( (i/n)^(1/n) ). Then filters it for values where n * x^n == i, sort the remaining pairs by their sum, and returns the first pair.
Try it online! or Verify all test cases.
Explanation
×*@¥/=³  Helper link. Input: list [n, x]
    /    Reduce using
   ¥       A dyadic chain
 *@        Compute x^n
×          Multiply by n
      ³  The initial value i
     =   Test if n * x^n == i

ṗ2ÇÐfSÞḢ  Main link (16 byte version). Input: integer i
ṗ2        Generate all pairs of integers in [1, i]
  ÇÐf     Filter for where the helper link is true
     SÞ   Sort them by their sum
       Ḣ  Return the first result

ÆDµṚ*İ⁸żḞÇÐfSÞḢ  Main link (23 byte version). Input: integer i
ÆD               Compute the divisors of i
  µ              Begin a new monadic chain operating on the divisors
   Ṛ             Reverse the divisors
     İ           Reciprocal of each divisors
    *            Raise each in the reversed divisors to the reciprocal of a divisor
      ⁸          Get the divisors
       ż         Interleave the divisors with the previous powers
        Ḟ        Floor each
         ÇÐf     Filter for where the helper link is true
            SÞ   Sort them by their sum
              Ḣ  Return the first result

PHP, 104 Bytes
for(;1<$x=(($i=$argv[1])/++$n)**(1/$n);)!($x==ceil($x))?:$a[$x+$n]="[$x, $n]";ksort($a);echo$a[key($a)];

This outputs all possible solutions not in the proposed format 73 Bytes
for(;1<=$x=(($i=$argv[1])/++$n)**(1/$n);)!($x==ceil($x))?:print"$x,$n\n";

Perl, 52 bytes
Includes +2 for -ap
Give input on STDIN
mono.pl <<< 33044255768277

mono.pl:
#!/usr/bin/perl -ap
$_=("@F"/++$.)**(1/$.)while!/\./?$\="$. $_":$_>2}{

Took some effort to make it work for 1 too. I have no idea if floating point errors can make this return the wrong answer for some inputs.


text:
Print a layered cake
Challenge
Given an input n, print an ASCII art cake n layers tall, viewed from the side, with two candles on top. Refer to the examples below for details.
Output
>> cake(1)

 _|_|_
|     |
+-----+

>> cake(3)

     _|_|_
    |     |
  +---------+
  |         |
+-------------+
|             |
+-------------+

...and so on.
Rules

Standard loopholes prohibited
Please make an attempt at a clever solution
This is code-golf, so shortest answer in bytes wins. However, the answer will not be selected.

Have fun!

Python 2, 238 chars
i=input()
m=["+"+"-"*(i*4+1)+"+","|"+" "*(i*4+1)+"|"]
for v in range(i,1,-1):
 m+=[" "*(i-v)*2+"+"+"-"*(v*4+1)+"+"," "*(i-v+1)*2+"|"+" "*((v-1)*4+1)+"|"]
m.pop()
m+=[" "*(i-1)*2+"|"+" "*5+"|"," "*(i-1)*2+" _|_|_"]
print'\n'.join(m[::-1])

The missing example of Cake 2:
   _|_|_
  |     |
+---------+
|         |
+---------+

Hello, and welcome to the site! You could take input from STDIN and take off 24 chars. For example, i=int(input())

If you want, you should be able to change to Python 2 and change int(input()) to input() and the print statement, plus you can change the four spaces to one (if it's a tab, change it to a space to make it more obvious that it's one character). Plus your bytecount is 4 too high for some reason.

@Mars Ultor oops, yes, I'm not sure why I chose python 3 to begin with. Thanks.

You may also be able to save a few bytes using percent formatting

Ruby, 109 107 bytes
->n{p=->t{puts t.center 3+4*n}
p['_|_|_']
(1..n).map{|i|p[?|+' '*(1+4*i)+?|]
p[?++?-*((i<n ?5:1)+4*i)+?+]}}

JavaScript (ES6), 134 bytes
A recursive cake.
f=(n,i=--n,r=(n,c)=>'- '[+!c].repeat(n),p=r((i-n)*2),j=n*4+5,x=p+`+${r(j,1)}+
`)=>(n?f(n-1,i)+x:p+` _|_|_
`)+p+`|${r(j)}|
`+(n-i?'':x)

Demo

let f=(n,i=--n,r=(n,c)=>'- '[+!c].repeat(n),p=r((i-n)*2),j=n*4+5,x=p+`+${r(j,1)}+
`)=>(n?f(n-1,i)+x:p+` _|_|_
`)+p+`|${r(j)}|
`+(n-i?'':x)

console.log(f(4))

Batch, 233 bytes
@echo off
set i=
for /l %%j in (2,1,%1)do call set i=  %%i%%
echo %i% _^|_^|_
set s=-----
for /l %%j in (2,1,%1)do call:l
echo ^|%s:-= %^|
echo +%s%+
exit/b
:l
echo %i%^|%s:-= %^|
set i=%i:~2%
set s=----%s%
echo %i%+%s%+

Shorter than Python? Something must be wrong...

Haskell, 103 bytes
f(a:b)n=a:([0..4*n]>>b)++[a]
x!n=x:[f"| "n,f"+-"n]
g 1=" _|_|_"!1
g n=map("  "++)(init.g$n-1)++f"+-"n!n

Defines a function g which returns a list of strings containing the lines of the output

05AB1E, 115, 101 chars
>UXð×?" _|_|_",Xð×?"|     |",X<U0<VXGNVXY-ð×?'+?8Y·+G'-?}'+,XY-ð×?'|?7Y·+ð×?'|,}XY-ð×?'+?8Y·+G'-?}'+,

Saved 14 chars thanks to Adnan!
Definitely some room for golfing here.
Try it online!
Note that this does print everything offset by one space.

Welcome to Programming Puzzles and Code Golf! Very nice first answer :)

Maybe string multiplication helps, which is the × command. This is an example on how it's used.

@Adnan That does help! Thanks!

Python 2, 122 bytes
a='  '*input()
b='+-+'
c=d=' '
while a:b='+----'+b[1:];c=d*4+c;a=a[2:];print a+[' _|_|_',b][c>d*5]+'\n%s|%%s|'%a%c
print b

Python 3, 162 characters
p=print
t=int(input())
d=4*'-'
s='  '
a='+\n'
r=(t-1)*s
p(r+' _|_|_\n'+r+'|     |')
for i in range(2,t+1):b=(t-i)*s;p(b+'+-'+i*d+a+b+'| '+i*2*s+'|')
p('+-'+t*d+a)

It's not very clever, but I've never done one of these before. (Edit: removed unnecessary parentheses; reduced by one more character)

Welcome to the site, and nice first answer!

Pyth, 73 bytes
+K*dtyQ"_|_|_"+tK"|     |"jP.iJms[*\ yt-Qd\+*+5*4d\-\+)+StQtQmXd"+-""| "J

A program that takes input of an integer on STDIN and prints the result.
There is probably still some golfing to be done here.
Try it online
Explanation coming later

JavaScript (ES6), 171 bytes
n=>[(s="  "[R='repeat'](n-1))+" _|_|_",s+"|     |",...Array(n-1),`+${"-"[R](n*4+1)}+`].map((_,i)=>_||(s="  "[R](n-i))+`+${"-"[R](i=i*4+1)}+`+`
${s}|${" "[R](i)}|`).join`
`

First pass, probably not optimal...

PHP, 150 147 138 136 130 140 bytes
new approach:
echo$p=str_pad("",-2+2*$n=$argv[1])," _|_|_";for($x="    ",$b=$y="----";$n--;){$a.=$x;if($n)$b.=$y;echo"
$p| $a|
",$p=substr($p,2),"+-$b+";}

old version for reference:
$p=str_pad;for($o=["_|_|_"];$i++<$n=$argv[1];$o[]="+".$p("",($i<$n)*4+$e,"-")."+")$o[]="|".$p("",$e=$i*4+1)."|";foreach($o as$s)echo$p($s,$n*4+3," ",2),"
";

I’m curious; how does this read input?

@Lynn: damn I forgot that this time.10 bytes overhead for $argv. :-/

Vimscript, 116 115 bytes
Pretty messy but it works!
fu A(n)
let @z="Vkyjply4lpjy4hp"
exe "norm 2i+\e5i-\eo||\e5i \e".a:n."@zddl4xggd$i_|_|_"
exe "%ce ".(a:n*4+3)
endfu

To call it: call A(3) in an empty buffer. To load the function, source cake.vim
Explanation

2i+<Esc>5i-<Esc> writes the first line +-----+
o||<Esc>5i<Space><Esc> adds |     | on the second line
Vkyjply4lpjy4hp is saved in the macro @z - it visually selects both lines, yanks them, pastes them under and adds 4 dashes and spaces to them.
#@z repeats this # times
ddl4x deletes the last lines and remove for dashes to the bottom of the cake to make it equal with the top of the bottom layer
ggd$i_|_|_ replaces the first line by the top of the cake
%ce then centers the whole cake to the  width of the bottom layer! !

SOGL V0.12, 27 26 bytes
∫4*I:┌*╗1Ο;@*┐1Ο}⁴¹k┐╔2ΟΚ╚

Try it Here!
Explanation:
∫               }           for each in 1..input inclusive, pushing counter
 4*                           multiply by 4
   I                          increase by 1
    :                         duplicate; this will be used later
     ┌*                       repeat a dash pop times
       ╗1Ο                    encase them in plusses
          ;                   get the duplicate on the stacks top
           @*                 repeat a space pop times
             ┐1Ο              encase in vertical bars
                 ⁴          duplicate the item below ToS - the last line
                  ¹         wrap the stack in an array
                   k        remove the arrays first item
                    ┐       push "_"
                     ╔      push "|"
                      2Ο    encase 2 copies of the vertical bar in underscores
                        Κ   and prepend that to the array
                         ╚  center the array horizontally

Excel VBA, 139 130 127 Bytes
Anonymous VBE immediate window that takes input from cell A1 and outputs a cake to the VBE immediate window
For i=1To[A1]:s=Space(2*([A1]-i)):x=String(1+4*i,45):?s &IIf(i=1," _|_|_","+" &x &"+"):?s"|"Replace(x,"-"," ")"|":Next:?s"+"x"+

C (gcc), 158 153 bytes
-5 bytes thanks to ceilingcat.
i,l,s;p(c,s){printf("%*c%*.*s%c\n",i-~i,c,l,l,s,c);}f(n){s=memset(malloc(5*n),45,5*n);l=1;for(i=n;i--;p('|',""))l+=4,n+~i?p(43,s):p(32,"_|_|_");p(43,s);}

Try it online!

CJam, 79 bytes
l~4*):Z5:X{D'+'-C}:A{D'|SC}:B{X*1$N}:C];{SZX-Y/*}:D~" _|_|_"NB{XZ<}{X4+:X;AB}wA

Try it online

QBasic, 115 bytes
INPUT n
?SPC(n*2-1)"_|_|_
FOR i=1TO n
s=n*2-i*2
?SPC(s)"|"SPC(i*4+1)"|
?SPC(s-2)"+"STRING$(i*4+(i=n)*4+5,45)"+
NEXT

Ungolfed
Print the top line with the candles; then print the rest of the cake two lines at a time.
INPUT n
PRINT SPC(n * 2 - 1); "_|_|_"
FOR i = 1 TO n
  indent = n * 2 - i * 2
  PRINT SPC(indent); "|"; SPC(i * 4 + 1); "|"
  PRINT SPC(indent - 2); "+"; STRING$(i * 4 + (i = n) * 4 + 5, 45); "+"
NEXT

SPC, when used in a PRINT statement, emits the given number of spaces. Conveniently, when given a negative argument, it treats it as 0, so the fact that indent - 2 is -2 in the last iteration isn't a problem. STRING$ takes a count and a character code (here, 45 for -) and repeats the character that number of times. Here, we have to special-case the last line (when i=n) to be 4 hyphens shorter than it would otherwise be.

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


text:
String Distance
Challenge
Given an input of an all-lowercase string [a-z], output the total distance between the letters.
Example
Input: golf

Distance from g to o : 8
Distance from o to l : 3
Distance from l to f : 6

Output: 17

Rules

Standard loopholes forbidden
This is code-golf - shortest answer in bytes wins.
The alphabet can be traversed from either direction. You must always use the shortest path. (i.e the distance between x and c is 5).

Test cases
Input: aa
Output: 0

Input: stack
Output: 18

Input: zaza
Output: 3

Input: valleys
Output: 35

Jelly, 11 8 bytes
OIæ%13AS

Saved 3 bytes thanks to @Martin Ender.
Try it online! or Verify all test cases.
Explanation
OIæ%13AS  Input: string Z
O         Ordinal. Convert each char in Z to its ASCII value
 I        Increments. Find the difference between each pair of values
  æ%13    Symmetric mod. Maps each to the interval (-13, 13]
      A   Absolute value of each
       S  Sum
          Return implicitly

I came across æ% while reading through the built-ins the other day, and it was pretty much made for this (type of) problem: OIæ%13AS

I think this is 9 bytes (æ is two).

@elmigranto Jelly has a codepage that encodes each of its characters in one byte: https://github.com/DennisMitchell/jelly/wiki/Code-page

Haskell, 57 56 bytes
q=map$(-)13.abs
sum.q.q.(zipWith(-)=<<tail).map fromEnum

Usage example: sum.q.q.(zipWith(-)=<<tail).map fromEnum $ "valleys" -> 35.
How it works:
q=map$(-)13.abs                -- helper function.
                               -- Non-pointfree: q l = map (\e -> 13 - abs e) l
                               -- foreach element e in list l: subtract the
                               -- absolute value of e from 13

               map fromEnum    -- convert to ascii values
      zipWith(-)=<<tail        -- build differences of neighbor elements
  q.q                          -- apply q twice on every element
sum                            -- sum it up

Edit: @Damien saved one byte. Thanks!

thanks for the rotational distance trick (q.q)

Wow nice one! You can add map in the definition of q for one byte less

@Damien: well spotted. Thanks!

MATL, 14, 10 bytes
dt_v26\X<s

Try it online!
Thanks @Suever for saving 4 bytes!
Explanation:
d           % Take the difference between consecutive characters
 t_         % Make a copy of this array, and take the negative of each element
   v        % Join these two arrays together into a matrix with height 2
    26\     % Mod 26 of each element
       X<   % Grab the minimum of each column
         s  % Sum these. Implicitly print

Previous version:
d26\t13>26*-|s

Python 3, 69 68 bytes
lambda s:sum([13-abs(13-abs(ord(a)-ord(b)))for a,b in zip(s,s[1:])])

Breakdown:
lambda s:
         sum(                                                      )
             [                             for a,b in zip(s,s[1:])]
              13-abs(13-abs(ord(a)-ord(b)))

You can lose one byte by removing the space before for

@Dopapp Oh yes, thanks!

You could take the input as a list of characters and use recursion to save 3 bytes: f=lambda a,b,*s:13-abs(13-abs(ord(a)-ord(b)))+(s and f(b,*s)or 0)

Java, 126 120 117 bytes
int f(String s){byte[]z=s.getBytes();int r=0,i=0,e;for(;++i<z.length;r+=(e=(26+z[i]-z[i-1])%26)<14?e:26-e);return r;}

Thanks to @KevinCruijssen for pointing out a bug in the original version and suggesting to make the for-loop empty.
The use of (26 + z[i] - z[i - 1]) % 26) is inspired from a comment by @Neil on another answer. (26 + ...)%26 serves the same purpose as Math.abs(...) because of ...? e : 26 - e.
Ungolfed:
int f(String s) {
    byte[]z = s.getBytes();
    int r = 0, i = 0, e;
    for (; ++i < z.length; r += (e = (26 + z[i] - z[i - 1]) % 26) < 14 ? e : 26 - e);
    return r;
}

Welcome to the site! What language is this? How many characters/bytes is it? You should [edit] those details into the top of your post, with this markdown: #Language, n bytes`

Ok. Thanks. I've edited it. Any improvement? :)

Yes, much better. :)

You're missing a - before an e in your ungolfed version.

Oh...thanks @Neil. It's fixed now.

Welcome to PPCG! Hmm, I'm getting a "Type mismatch: cannot convert from int to byte" error at e=z[i]-z[i-1]; So you either need a cast to (byte) or change the e to int. Also, you can remove the for-loop brackets by placing everything inside the for-loop, like this: int f(String s){byte[]z=s.getBytes();int r=0,i=0,e;for(;++i<z.length;r+=(e=z[i]-z[i-1])>0?e<14?e:26-e:-e<14?-e:e+26);return r;} (PS: The reversed the for-loop is unfortunately the same length: int f(String s){byte[]z=s.getBytes();int r=0,i=z.length-1,e;for(;i>0;r+=(e=z[i]-z[--i])>0?e<14?e:26-e:-e<14?-e:e+26);return r;}.

Thanks a lot @KevinCruijssen :D. Your suggestion has helped a lot.

JavaScript (ES6), 84 82 79 bytes

Saved 3 bytes thanks to Cyoce:
f=([d,...s],p=parseInt,v=(26+p(s[0],36)-p(d,36))%26)=>s[0]?f(s)+(v>13?26-v:v):0

Explanation:
f=(
  [d,...s],                    //Destructured input, separates first char from the rest
  p=parseInt,                  //p used as parseInt
  v=(26+p(s[0],36)-p(d,36))%26 //v is the absolute value of the difference using base 36 to get number from char
  )
)=>
  s[0]?                        //If there is at least two char in the input
    f(s)                       //sum recursive call
    +                          //added to
    (v>13?26-v:v)              //the current shortest path
  :                            //else
    0                          //ends the recursion, returns 0

Example:
Call: f('golf')
Output: 17

Previous solutions :
82 bytes thanks to Neil:
f=([d,...s],v=(26+parseInt(s[0],36)-parseInt(d,36))%26)=>s[0]?f(s)+(v>13?26-v:v):0

84 bytes:
f=([d,...s],v=Math.abs(parseInt(s[0],36)-parseInt(d,36)))=>s[0]?f(s)+(v>13?26-v:v):0

Instead of Math.abs(...) you can use (26+...)%26; this works because you're flipping values above 13 anyway. (I think this is how the MATL answer works.)

Save some bytes by prepending the code with p=parseInt; and then using p() instead of parseInt()

Ruby, 73 bytes
->x{eval x.chars.each_cons(2).map{|a,b|13-(13-(a.ord-b.ord).abs).abs}*?+}

PHP, 93 Bytes
for(;++$i<strlen($s=$argv[1]);)$r+=13<($a=abs(ord($s[$i-1])-ord($s[$i])))?$a=26-$a:$a;echo$r;

05AB1E, 12 bytes
SÇ¥YFÄ5Ø-}(O

Explanation
SÇ                   # convert to list of ascii values
  ¥                  # take delta's
   YF    }           # 2 times do
     Ä5Ø-            # for x in list: abs(x) - 13
          (O         # negate and sum

Try it online!

It's 12 symbols, not bytes. Byte-length would be 16 for UTF-8.

@elmigranto: Indeed. In UTF-8 that would be the case, but 05AB1E uses CP-1252 where this is 12 bytes.

Racket 119 bytes
(λ(s)(for/sum((i(sub1(string-length s))))(abs(-(char->integer
(string-ref s i))(char->integer(string-ref s(+ 1 i)))))))

Testing:
(f "golf")

Output:
17

Detailed version:
(define(f s)
  (for/sum((i(sub1(string-length s))))
    (abs(-(char->integer(string-ref s i))
          (char->integer(string-ref s(+ 1 i)))))))

You could replace (define(f s) with (lambda(s), 2 bytes shorter (anonymous functions are fine).

Wait, Racket should take (λ(s) too, which if in utf8 is 6 bytes i think

Perl, 46 bytes
Includes +3 for -p (code contains ')
Give input on STDIN without final newline:
echo -n zaza | stringd.pl

stringd.pl:
#!/usr/bin/perl -p
s%.%$\+=13-abs 13-abs ord($&)-ord$'.$&%eg}{

Actually, 21 bytes
Based partially on cia_rana's Ruby answer.
There was a bug with O (in this case, map ord() over a string) where it would not work with d (dequeue bottom element) and p (pop first element) without first converting the map to a list with #. This bug has been fixed, but as that fix is newer than this challenge, so I've kept # in.
Edit: And the byte count has been wrong since September. Whoops.
Golfing suggestions welcome. Try it online!
O#;dX@pX♀-`A;úl-km`MΣ

Ungolfing
         Implicit input string.
          The string should already be enclosed in quotation marks.
O#       Map ord() over the string and convert the map to a list. Call it ords.
;        Duplicate ords.
dX       Dequeue the last element and discard it.
@        Swap the with the duplicate ords.
pX       Pop the last element and discard it. Stack: ords[:-1], ords[1:]
♀-       Subtract each element of the second list from each element of the first list.
          This subtraction is equivalent to getting the first differences of ords.
`...`M   Map the following function over the first differences. Variable i.
  A;       abs(i) and duplicate.
  úl       Push the lowercase alphabet and get its length. A golfy way to push 26.
  -        26-i
  k        Pop all elements from stack and convert to list. Stack: [i, 26-i]
  m        min([i, 26-i])
Σ        Sum the result of the map.
         Implicit return.

C#, 87 85 bytes
Improved solution - replaced Math.Abs() with the add & modulo trick to save 2 bytes:
s=>{int l=0,d,i=0;for(;i<s.Length-1;)l+=(d=(s[i]-s[++i]+26)%26)>13?26-d:d;return l;};

Initial solution:
s=>{int l=0,d,i=0;for(;i<s.Length-1;)l+=(d=Math.Abs(s[i]-s[++i]))>13?26-d:d;return l;};

Try it online!
Full source, including test cases:
using System;

namespace StringDistance
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<string,int>f= s=>{int l=0,d,i=0;for(;i<s.Length-1;)l+=(d=Math.Abs(s[i]-s[++i]))>13?26-d:d;return l;};

            Console.WriteLine(f("golf"));   //17
            Console.WriteLine(f("aa"));     //0
            Console.WriteLine(f("stack"));  //18
            Console.WriteLine(f("zaza"));   //3
            Console.WriteLine(f("valleys"));//35
        }
    }
}

Java 7,128 bytes
 int f(String s){char[]c=s.toCharArray();int t=0;for(int i=1,a;i<c.length;a=Math.abs(c[i]-c[i++-1]),t+=26-a<a?26-a:a);return t;}

Ungolfed
 int f(String s){
 char[]c=s.toCharArray();
 int t=0;
 for(int i=1,a;
     i<c.length;
   a=Math.abs(c[i]-c[i++-1]),t+=26-a<a?26-a:a);
return t;
 }

Pyth, 20 bytes
Lm-13.adbsyy-M.:CMQ2

A program that takes input of a quoted string on STDIN and prints the result.
Try it online
How it works
Lm-13.adbsyy-M.:CMQ2  Program. Input: Q
L                     def y(b) ->
 m      b              Map over b with variable d:
  -13                   13-
     .ad                abs(d)
                CMQ   Map code-point over Q
              .:   2  All length 2 sublists of that
            -M        Map subtraction over that
          yy          y(y(that))
         s            Sum of that
                      Implicitly print

C#, 217 bytes
Golfed:
IEnumerable<int>g(string k){Func<Char,int>x=(c)=>int.Parse(""+Convert.ToByte(c))-97;for(int i=0;i<k.Length-1;i++){var f=x(k[i]);var s=x(k[i+1]);var d=Math.Abs(f-s);yield return d>13?26-Math.Max(f,s)+Math.Min(f,s):d;}}

Ungolfed:
IEnumerable<int> g(string k)
{
  Func<Char, int> x = (c) => int.Parse("" + Convert.ToByte(c)) - 97;
  for (int i = 0; i < k.Length - 1; i++)
  {
    var f = x(k[i]);
    var s = x(k[i + 1]);
    var d = Math.Abs(f - s);
    yield return d > 13 ? 26 - Math.Max(f, s) + Math.Min(f, s) : d;
  }
}

Output:
aa: 0
stack: 18
zaza: 3
valleys: 35

'a' is 97 when converted to bytes, so 97 is subtracted from each one. If the difference is greater than 13 (ie, half of the alphabet), then subtract the differences between each character (byte value) from 26. A last minute addition of "yield return" saved me a few bytes!

Two useless whitespaces: both before 's'.

dc + od, 65 bytes
od -tuC|dc -e'?dsN0sT[lNrdsNr-d*vdD[26-]sS<Sd*vlT+sTd0<R]dsRxlTp'

Explanation:
Because in dc you can't access a string's characters, I used od to get the ASCII values. These will be processed in reverse order from the stack (LIFO container) like so:
dsN0sT             # initialize N (neighbor) = top ASCII value, and T (total) = 0
[lNrdsNr-          # loop 'R': calculate difference between current value and N,
                   #updating N (on the first iteration the difference is 0)
   d*vdD[26-]sS<S  # get absolute value (d*v), push 13 (D) and call 'S' to subtract
                   #26 if the difference is greater than 13
   d*vlT+sT        # get absolute value again and add it to T
d0<R]dsR           # repeat loop for the rest of the ASCII values
xlTp               # the main: call 'R' and print T at the end

Run:
echo -n "golf" | ./string_distance.sh

Output:
17

C, 82 86 83 76 bytes
t,u;f(char*s){for(t=0;*++s;u=*s-s[-1],t+=(u=u<0?-u:u)>13?26-u:u);return t;}

Assumes input string is at least one character long. This doesn't require #include<stdlib.h>
Edit: Argh, sequence points!
Try it on Ideone

in ideone compiler the string "nwlrbb" and all the rand string i try 6 len return all 0 but it seems not 0 the result....

yes now it seems ok...

Scala, 68 bytes
def f(s:String)=(for(i<-0 to s.length-2)yield (s(i)-s(i+1)).abs).sum

Criticism is welcome.

C, 70 bytes 76 bytes
k,i;f(char *s){for(i=0;*++s;i+=(k=abs(*s-s[-1]))>13?26-k:k);return i;}

Python 3, 126 bytes
With list incomprehension.
d=input()
print(sum([min(abs(x-y),x+26-y)for x,y in[map(lambda x:(ord(x)-97),sorted(d[i:i+2]))for i in range(len(d))][:-1]]))

Nice answer. You could replace abs(x-y) by y-x since the call to sorted make x < y.

Java, 109 bytes
int f(String s){int x=0,t,a=0;for(byte b:s.getBytes()){t=a>0?(a-b+26)%26:0;t=t>13?26-t:t;x+=t;a=b;}return x;

PHP, 79 bytes
for($w=$argv[1];$w[++$i];)$s+=13-abs(13-abs(ord($w[$i-1])-ord($w[$i])));echo$s;


text:
Interpret Repetition!
This challenge is the first in a two-challenge series about Repetition. The second will be up soon.
In a language called Repetition (something I just made up), there consists an infinite string of 12345678901234567890..., with 1234567890 repeating forever.
The following syntax is available to output numbers:

+-*/: This inserts the operator into the string of repeating digits.

Examples:

+ -> 1+2 = 3 (The + inserts a + between 1 and 2)
+* -> 1+2*3 = 1+6 = 7 (Same as above, except two operators are used now)
/ -> 1/2 = 0 (Repetition uses integer division)
// -> 1/2/3 = 0/3 = 0 (Repetition uses "left association" with multiple subtractions and divisions)

Each operator is inserted so that it has one digit to its left, unless there are c's (see below).

c: Concatenates with the next digit in the string.

Examples:

c+ -> 12+3 = 15 (The c "continues" the 1 and concatenates it with the next digit, 2, to form 12)
+c -> 1+23 = 24
ccc -> 1234

(): Brackets for processing numbers.

Examples:

(c+)* -> (12+3)*4 = 15*4 = 60 (Repetition uses the order of operations)
(c+)/c -> (12+3)/45 = 15/45 = 0
(cc+c)/ -> (123+45)/6 = 168/6 = 28

s: Skip a number (removes the number from the infinite string).

s+ -> 2+3 = 5 (s skips 1)
csc -> 124 (The first c concats 1 and 2, the s skips 3, and the final c concats 12 to 4)
+s+ -> 7 (The first + adds 1 and 2 to make 3, s skips 3, and the final + adds 3 to 4 to make 7)
cs*(++) -> 12*(4+5+6) = 12*15 = 180

In the examples above, only a finite amount of digits in the infinite string are used. The number of digits used is equivalent to number of operators, concats and skips + 1.
Your task is, when given a string of Repetition code, output the result.
Examples of input and output are:
++ -> 6
- -> -1
(-)* -> -3
cscc -> 1245
(cc+c)/ -> 28
cc+c/ -> 130
cs*(++) -> 180

This is code golf, so shortest code in bytes wins!
Specs:

You are guaranteed that the result will never go above 2^31-1.
You are also guaranteed that the input will only consist of the symbols +-*/cs().
An empty program will output 1.

What about the ~s? Don't leave us hanging.

@RobertFraser Whoops, that was a mistake - c was originally ~, but it appears that I haven't fixed that completely.

Obviously directly after a ) there shouldn't be a number in the resulting expression. Therefore. no c or ( directly after ) in the input. But can there be a s directly after ) ? And likewise can there be a s just before ( ?. I'd prefer only operators or string end just before or after ()...

@TonHospel Ooh, you've got a good point there. The "s" symbol essentially removes the number it's associated with from the infinite string altogether, so it's a yes for both scenarios.

cc+c/=> 123+45/6 => 123+7 => 130. Or did I miss something? (you wrote 52 in your examples)

@Dada Ah yeah, now that I think about it, I have no idea how I got 52. Thanks for the correction!

What's the output of sc? 23 as in s+ or 13 as in csc?

@jimmy23013 s skips 1, so the output would be 23. (Also, how does s+ output 23?)

@Qwerp-Derp So it isn't possible to skip 2 and use c to output 13?

@jimmy23013 Yeah, as you can't s on the first one (because that would skip 1), and you can't c (because then you have 12).

The way  s works still seems strange.because it remains unclear in what state the digit sequence is left after each language element. What is the expression for +s+ ? 1+2+4 or 1+3+4 ? 1+3+4 seems most logical, but then I would also expect csc to give 134 and not 124

@TonHospel + adds 1 and 2, s skips 3, and + adds an additional 4. The same goes for c: c concats 1 and 2 to become 12, s skips 3, and c concats 12 and 4 to become 124. I should probably add those as examples.

So the + seems to consume the 2 so it's not there for s anymore. So how about +(s)+ ? 1+(2)+4 or 1+(3)+4 ?

@TonHospel It doesn't make a difference. It's 1+(2)+4.

Ok, so s acts "late". That would however make me expect 1+3 for s+ otherwise s at the start of the string will need special handling

Your specification however says s+ is 2+3 as its first example. And still s keeps bugging me. I wonder how +s()+ expands. If it is 1+(2)+4 then ( comes before 2 but the s that comes even before the ( seemingly still skips 3, not 2. If however the result is 1+(3)+4 then the effect of a s depends on what comes after it (compare it with +s+)

sc is 23 and s+ is 1+3? Does s skip the 1 now or the 2? All examples use the first operation on operands 1 and 2 ... so sc should be 13.

@Titus Sorry about that, s+ is 2+3.

Surely // -> 1/2/3 = 0.5/3 = 6 is wrong. Wouldn’t it equal 0/3 = 0?

@Lynn Ah yeah, sorry. I got confused with 3/0.5. Thanks for catching that!

So what exactly happens with +sc?? If it's 1+34 then why isn't +s+=1+3+4 (skipping before taking a digit), and if it's 1+24 then why isn't sc=13 (skipping after taking a digit) and if it's (1+2)4=34 then why isn't +c=(1+2)3=33 (adding before concatenating).

JavaScript (ES6), 110 bytes
s=>eval((" "+s)[R='replace'](/[^\)](?!\()/g,x=>x+i++%10,i=1)[R](/c| (\ds)+|s\d/g,"")[R](/\d+\/\d+/g,"($&|0)"))

Very simple, but integer division adds 25 bytes. For some reason a regex in JS can't match both the beginning of a string and the first character, so that adds a few bytes as well.
How it works

Prepend a space to the input.
Append the next digit to each character (except )) that isn't immediately before a (.
Remove each c, a digit + s at the beginning (1s2 -> 2), and each s + a digit (3s4 -> 3).
Turn each division operation into int-division (1/2 -> (1/2|0)).
Evaluate and return.

OK... your program has a bug... ss+ returns 6, when it's meant to return 7 (The two s's skip 1 and 2, so the + adds 3 and 4).

@Qwerp-Derp Thanks, fixed.

Something like /^|,|$/g will only match once at the beginning because both matches would have the same index. $ doesn't have the same problem because the match has a greater index than any other possible match.

Batch, 332 bytes
@echo off
set s=
set e=
set d=
set r=
set/ps=
:d
set/ad=-~d%%10
:l
if "%s%"=="" goto g
set c=%s:~0,1%
set s=%s:~1%
if %c%==( set e=%e%(&goto l
if %c%==) set r=%r%)&goto l
if %c%==s goto d
if %c%==c set c=
if "%r%"=="" set/ar=d,d=-~d%%10
set e=%e%%r%%c%
set/ar=d
goto d
:g
if "%r%"=="" set/ar=d
cmd/cset/a%e%%r%

The behaviour of s makes this very awkward. (Maybe cs should evaluate to 13 and -s to -2?) Variables:

s input string (explicitly blanked out because set/p doesn't change the variable if you don't input anything)
e partial expression in normal integer arithmetic (which we can pass to set/a as a form of eval)
d next digit from the infinite string of digits
r right hand side of latest operator. We can't concatenate this immediately because ( needs to come first, but we need to store it so that s won't increment it. Fortunately it does end up making the handling of ) slightly easier.
c current character.