# -*- coding: utf-8 -*-
"""
tube.expand
~~~~~~~~~~~

This module defines various utilities for expanding special placeholders
inside commands.
"""

import re


def cr(rawstr):
    """To replace the character sequence `<CR>` into a newline.

    If `<CR>` is prepended with a backslash, the replacement is not performed.
    """
    out = re.sub(r"(?<!\\)<CR>", "\n", rawstr, flags=re.IGNORECASE)
    return re.sub(r"\\(<cr>)", "\\1", out, flags=re.IGNORECASE)


def character(rawstr, target, repl):
    """To replace the character `target` with `repl` in `rawstr`.

    If `target` is prepended with a backslash, the replacement is not performed.
    """
    out = re.sub("(?<!\\\\){0}".format(target), repl, rawstr)
    return re.sub("\\{0}".format(target), target, out)

@@ -644,37 +644,38 @@
 ed.%0A    %22%22%22%0A    
-out =
+return
  re.sub(%22(?%3C!%5C%5C%5C
@@ -671,17 +671,10 @@
 ub(%22
-(?%3C!%5C%5C
 %5C%5C
-)
 %7B0%7D%22
@@ -694,40 +694,38 @@
 t), 
-repl, rawstr)%0A    return
+target, out)%0A    out =
  re.sub(
 %22%5C%5C%7B
@@ -712,35 +712,41 @@
    out = re.sub(
-%22
+r%22(?%3C!
 %5C%5C
+)
 %7B0%7D%22.format(targ
@@ -742,29 +742,30 @@
 format(target), 
-target, out
+repl, rawstr
 )%0A

Use raw strings