Quantcast
Channel: Implement LaTeX accent macros - Code Golf Stack Exchange
Viewing all articles
Browse latest Browse all 6

Answer by Alex A. for Implement LaTeX accent macros

$
0
0

Julia, 204 184 bytes * 0.9 = 165.6

x->(r=r"\\(\w)\w+{(\w)}";t=[""^endof(x)...];while ismatch(r,x) m=match(r,x);(a,b)=m.captures;t[m.offsets[1]-1]=a=="b"?'_':a=="d"?'.':a=="h"?'^':'~';x=replace(x,r,b,1)end;(join(t),x))

This is an anonymous function that accepts a string and returns a tuple of strings corresponding to the top and bottom lines. The top line will have trailing whitespace. To call the function, give it a name, e.g. f=x->...

Ungolfed:

function f(x::AbstractString)    # Store a regular expression that will match the LaTeX macro call    # with capture groups for the first letter of the control sequence    # and the character being accented    r = r"\\(\w)\w+{(\w)}"    # Create a vector of spaces by splatting a string constructed with    # repetition    # Note that if there is anything to replace, this will be longer    # than needed, resulting in trailing whitespace    t = [""^endof(x)...]    while ismatch(r, x)        # Store the RegexMatch object        m = match(r, x)        # Extract the captures        a, b = m.captures        # Extract the offset of the first capture        o = m.captures[1]        # Replace the corresponding element of t with the accent        t[o-1] = a == "b" ? '_' : a == "d" ? '.' : a == "h" ? '^' : '~'        # Replace this match in the original string        x = replace(x, r, b, 1)    end    # Return the top and bottom lines as a tuple    return (join(t), x)end

Viewing all articles
Browse latest Browse all 6

Trending Articles