[Question]
  [
Given a string of ASCII letters (upper and/or lower case), output the raw MathJax required to display that string bifurcating at each character, into superscripts and subscripts. For example, the inputs `cat` and `horse` would result in outputs which MathJax renders as the following, respectively:
[![image of cat bifurcating](https://i.stack.imgur.com/oo1cl.png "bifurCat")](https://i.stack.imgur.com/oo1cl.png "bifurCat")
[![image of horse bifurcating](https://i.stack.imgur.com/73LLx.png)](https://i.stack.imgur.com/73LLx.png)
Note that only one input is required to be taken - these two are listed side by side simply to save vertical space.
# Markup meaning
* `_` indicates a subscript.
* `^` indicates a superscript.
* Braces are required around superscripted or subscripted substrings that contain further superscripting or subscripting in order to prevent them all being at the same level.
# Test cases
Test cases are in the format `input : output`. The first test case shows the empty string as input should result in the empty string as output.
```
"" : ""
"a" : "a"
"me" : "m_e^e"
"cat" : "c_{a_t^t}^{a_t^t}"
"frog" : "f_{r_{o_g^g}^{o_g^g}}^{r_{o_g^g}^{o_g^g}}"
"horse" : "h_{o_{r_{s_e^e}^{s_e^e}}^{r_{s_e^e}^{s_e^e}}}^{o_{r_{s_e^e}^{s_e^e}}^{r_{s_e^e}^{s_e^e}}}"
"bifurcate" : "b_{i_{f_{u_{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}^{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}}^{u_{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}^{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}}}^{f_{u_{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{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_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}}}}"
```
You can see how these are rendered by pasting the output into [mathurl.com](http://mathurl.com/).
# No redundant braces
MathJax will happily render markup that has redundant braces. For example, the following will all look identical when rendered: `a`, `{a}`, `{}{a}`, `{{{{a}}}}`.
However, valid output for this challenge has no redundant braces. Note in particular that single characters in the output are not surrounded by braces.
# Order
The order of subscript and superscript is unimportant. The following are equivalent and will be indistinguishable when rendered (and are all equally valid outputs):
```
c_{a_t^t}^{a_t^t}
c_{a^t_t}^{a_t^t}
c_{a_t^t}^{a^t_t}
c_{a^t_t}^{a^t_t}
c^{a_t^t}_{a_t^t}
c^{a^t_t}_{a_t^t}
c^{a_t^t}_{a^t_t}
c^{a^t_t}_{a^t_t}
```
# Scoring
For each language, the winner is the shortest code in bytes.
Too many notifications? Type `</sub>` to unsubscript
  
[Answer]
# Python, ~~95~~ ~~90~~ ~~86~~ ~~92~~ 82 bytes
*10 bytes saved thanks to @ConnerJohnston*
```
f=lambda s:s and s[0]+(s[1:]and'_{0}^{0}'.format(s[2:]and'{'+f(s[1:])+'}'or s[1]))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRodiqWCExL0WhONogVlujONrQKhbIVY@vNqiNA2J1vbT8otzEEqCMEUSmWl07DaJOU1u9Vj2/CKjVMFZT839BUWZeiUaahrq6piYXnJOIyktC4WbkFxWnAkX@AwA)
[Answer]
# Mathematica, ~~72~~ ~~84~~ ~~77~~ 76 bytes
```
a_±b__:={"{",a,"_",±b,"^",±b,"}"};±(a_:""):={"",a,""};""<>Most@Rest@±##&@@#&
```
Uses CP-1252 (Windows) encoding. Takes a list of characters as input.
## Explanation
```
a_±b__:=
```
Define the function `±`, with 2 or more arguments. Label the first argument `a`, and second and on `b`.
```
{"{",a,"_",±b,"^",±b,"}"}
```
Create a `List` equivalent to `"{a_±b^±b}"` (`±b` is evaluated again, recursively).
```
±(a_:""):= ...
```
Define the function `±`, with 1 or 0 arguments. Label the first argument`a`, if it exists, and assign `""` to `a` otherwise.
```
{"",a,""}
```
Create a `List` equivalent to `"a"`, padded with empty `String`s.
```
""<>Most@Rest@±##&@@#&
```
A pure function that applies `±` to the input, drops first and last element, and converts `List` to `String`.
[Answer]
## CJam (35 bytes)
```
MqW%{"^{ }_{ }"{AW$,)3e<#<},S/@*+}/
```
This is a full program. [Online demo](http://cjam.aditsu.net/#code=MqW%25%7B%22%5E%7B%20%7D_%7B%20%7D%22%7BAW%24%2C)3e%3C%23%3C%7D%2CS%2F%40*%2B%7D%2F&input=abcde).
3 bytes work around a bug in the interpreter (see below).
### Dissection
```
M            e# Start building from the empty string
qW%{         e# For each character in the reversed input
  "^{ }_{ }" e#   Take a template
  {          e#   If the accumulator is of length n, remove all characters whose
    A        e#   codepoints are greater than pow(10,
    W$,)3e<  e#                                   min(n+1, 3))
    #<       e#   When the accumulator is the empty string, that's all of them.
  },         e#   When the accumulator is one character, that's {}
             e#   When the accumulator is any longer, it's none of them.
  S/@*       e#   Substitute the accumulator for the spaces.
  +          e#   Append to the new character.
}/
```
Note that the `min(n+1, 3)` is to work around a bug in the interpreter: there must be some pattern in the powers of 10 that `'}` is smaller than, but [it's not obvious](http://cjam.aditsu.net/#code='%7DA50%2Cf%23f%3C).
[Answer]
## JavaScript (ES6), ~~57~~ 55 bytes
```
f=([c,...s])=>s+s?c+`_${p=s[1]?`{${f(s)}}`:s}^`+p:c||''
```
~~Θ(len(s)) complexity!~~ According to @PeterTaylor, this is actually Θ(2^len(s)), which is still the best possible...
[Answer]
# [Haskell](https://www.haskell.org/), 71 bytes
```
f[x,y]=x:'_':y:'^':y:[]
f(x:y@(_:_))=x:"_{"++f y++"}^{"++f y++"}"
f x=x
```
[Try it online!](https://tio.run/##7VVdaoQwEH73FCEsmKC9QMDSC/QEVkPWJirVVUykkdCz24lmoXRf9qWUUl8yM9988xcGphH6TXbduqrcpkuRWRbzmC0sLv2bF5Eili1PhDNOKXgxdzhJFFqSBH@UX3QcKWQzu0or@rGTOssJxinCmKYRIlh4XQSjl97quSxlQCphPFRxJ7gpDWTeZXCraai9X3E3cTfwuqyBsktQbrEQ1wyT3mo1nuF52hcF3i732G/YluVebih0btU8wRBbsTN3LXfQ67yl2YZyJgSaa7JbDLT7uXs7P5Qb9L/bOxjH3//W34N17P6x@/9z9zEtol60l6wX4zMiL0SnSFL08IjGqb2Yk4ZDyRDcTKKb4f0ks0whTQFERNpRVka@MvBKj4jKzKLzJgkkiim6Xtf1Ew "Haskell – Try It Online")
If we just had to output valid code the following would work for 44 bytes:
```
f[a]=[a]
f(a:b)=a:"_{"++f b++"}^{"++f b++"}"
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/Py06MdYWiLnSNBKtkjRtE62U4quVtLXTFJK0tZVq45DYSv9zEzPzbAuKMvNKVNKUkhNLlP4DAA "Haskell – Try It Online")
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), 21 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
±K;{╔+;lH?"{ŗ}”}1 ^Ο+
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JUIxSyUzQiU3QiV1MjU1NCslM0JsSCUzRiUyMiU3QiV1MDE1NyU3RCV1MjAxRCU3RDElMjAlNUUldTAzOUYr,inputs=Y2F0)
Explanation:
```
±                      reverse the string
 K                     take off the first letter - will slowly convert to the output
  ;                    get the rest of the string ontop
   {                   iterate over the rest of the characters
    ╔+                   append "_" to it
      ;                  get the output string ontop
       lH?     }         if it's length - 1 [isn't 0]
          "{ŗ}”            push the string "{ŗ}" where ŗ is replaced by the output string
                1 ^Ο     wrap "^" around with the output string
                    +    prepend to it the current character + "_"
```
[Answer]
# [Perl 5](https://www.perl.org/), 54 + 1 (-p) = 55 bytes
```
s/\{(.)\}/$1/g while s/([a-z])([a-z]+)/$1_{$2}^{$2}/ig
```
[Try it online!](https://tio.run/##K0gtyjH9/79YP6ZaQ08zplZfxVA/XaE8IzMnVaFYXyM6UbcqVhNCaWsCJeOrVYxq40CEfmb6//@JScn/8gtKMvPziv/r@prqGRga/NctAAA "Perl 5 – Try It Online")
**How?**
The substitution in the while condition breaks occurrences of multiple letters in the first letter, followed by the rest in braces like this:
```
abc -> a_{bc}^{bc}
```
The while loop executes the substitution until no more multi-letter sequences remain. The substitution inside the loop removes braces from around single letters.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~76~~ ~~73~~ ~~72~~ ~~68~~ ~~67~~ 57 bytes
Use of lambda saving 4 bytes thanks to [Tutleman](https://codegolf.stackexchange.com/users/64834/tutleman)
```
f=->s{(r=s[1..-1])[0]?s[0]+?_+[r[1]??{+f[r]+?}:r]*2*?^:s}
```
[Try it online!](https://tio.run/##FchBCsIwEEDRfU8xG0EbGozLQs1BhlFik9iNRmZaiqQ5e6ybD@/z8vjWGofuKvnIg6DRujN0wjNZ2aPsXSGjIWuzisj7KD1Te2ntrZdSD2t28AowuhkipydMiSUUHdw4gU@wrYn91gB8llkg4p/UhLevPw "Ruby – Try It Online")
Ungolfed:
```
def f(s)
  r = s[1..-1]
  if r.size > 0
    if r.size > 1
      x = "{" + f(r) + "}"
    else
      x = r
    end
    return s[0] + "_" + [x, x].join("^")
  else
    return s
  end
end
```
[Answer]
# [Python 2](https://docs.python.org/2/), 84 bytes
```
def b(s):q=s and(s[2:]and'{%s}'or'%s')%b(s[1:]);return s[1:]and s[0]+'^%s_'%q+q or s
```
[Try it online!](https://tio.run/##HYxBCsIwEAC/spewWXrRHiO@pMQSbcVeNsluShHx7XHxNgPDlHd7ZR57X9Yn3L1SqFeFxIvXaQzRAD9Ov5gFnSI5S6ZziHSRte3C8DerDE5xwJvTGV0dKmQB7UU2braVdMwbl715ov5I7Qc "Python 2 – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 47 bytes
```
Ljk[hb|&ttbs[\_\{ytb"}^{"ytb\})&tbs[\_htb\^htb;
```
[Try it online!](https://tio.run/##K6gsyfj/3ycrOzojqUatpCSpODomPqa6siRJqTauWglIx9RqqkGEM4CcOCBh/b/yv1JGflFxqhIA "Pyth – Try It Online")
This is pretty much a straight port of @Uriel's Python answer. Going to golf it down in a bit.
[Answer]
# PHP, 121 bytes
```
function b($s){return $s[0].($s[1]?'_'.($s[2]?'{'.($b=b(substr($s,1))).'}^{'.$b.'}':"$s[1]^$s[1]"):'');}echo b($argv[1]);
```
The function itself is 104 bytes and shows a PHP Notice.
[Answer]
# [Retina](https://github.com/m-ender/retina), 43 bytes
```
(.)(.)$
$1¶$2
+`(.)¶(.*)
¶{$1_$2^$2}
¶{|}$
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0NPE4hUuFQMD21TMeLSTgDyDm3T0NPS5Dq0rVrFMF7FKE7FqBbEqalV4fr/P5ErN5UrObGEK60oP50rI7@oOJUrKTOttAgolgoA "Retina – Try It Online") Link includes test cases. Explanation:
```
(.)(.)$
$1¶$2
```
Get the ball rolling by slicing off the last character. (But if it's the only character, them leave it alone.)
```
+`(.)¶(.*)
¶{$1_$2^$2}
```
Move the ¶ character back one step at a time, each time taking the previous result and making it a subscript and superscript of the next character.
```
¶{|}$
```
Remove the now redundant ¶ and the outer {}s.
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 121 bytes
```
s->{int l=s.length;String r=--l<0?"":""+s[l];for(;l-->0;)r="{"+s[l]+"_"+r+"^"+r+"}";return r.replaceAll("^\\{|\\}$","");}
```
[Try it online!](https://tio.run/##VVDBbsIwDL3zFZa1Q6vSiDOlTGjSbjtxpDCFLi1hIamcFAl1/fYupR10kZL42c/Wez7zK49NJfT567ur6qOSOeSKWwsfXGpoZgBj1jru/Hc18gsuvhZsHUld7vbAqbThnQpw9vNY7aRiRa1zJ41m72Owyk@cdvv50LeGoyxqyrkzBCl0Nl43UjtQqWVK6NKdkoEIlMaxWi1eEZeIkd2pfVIYChIVx@tFElKKzZCO8BMjivBwf1tMSLiaNBAjUSmei41SAR6yrPnJsvYF54hh0nbJXfjDjRPWWa9o8NMfxPkz5lNwEVPkvUxhQaac4pMh@4//twCBY64dpPTuRu@9mOUgKXwo2t6sExdmascqz3JKB89dMl5V6hb0LcyZN7/yDRG/BWEYDtPbWX/b7hc "Java (OpenJDK 8) – Try It Online")
[Answer]
# Javascript, 73 Bytes
```
s=>[...s].reduceRight((m,c)=>`${c}_{${m}}^{${m}}`).replace(/{(.)}/g,'$1')
```
## Explanation
```
s=>                                  // take the input string
    [...s]                           // split the string into an array
    .reduceRight(                    // reduce the array in reverse order
        (m,c)=>`${c}_{${m}}^{${m}}`  // storing the result of each iteration in the memo m
    )                                // and returning m at the end
    .replace(/{(.)}/g,'$1')          // replace redundant {}
```
Because there is no specified initial value of `m`, `reduceRight` takes the last element of `s` as the initial value, and begins iterating at index `s.length-2`.
```
const f=s=>[...s].reduceRight((m,c)=>`${c}_{${m}}^{${m}}`).replace(/{(.)}/g,'$1');
const input = document.querySelector('#input');
const output = document.querySelector('#output');
output.textContent = f(input.value);
input.addEventListener('keyup', e => output.textContent = f(input.value));
```
```
Enter text to bifurcate: <input type="text" id="input" value="cat" />
<br />
<span id="output"></span>
```
]