def fit_text(
    text,
    max_width,
    ommit_direction,
    font_height=ENC_SANS_BOLD_FONT_HEIGHT,
    font_path=ENC_SANS_BOLD_FONT_PATH,
    padding=0,
):
    """Return optimal text to fit max_width passed."""
    ### get font
    font = FONTS_DB[font_path][font_height]

    ### update max_width to take padding into account
    max_width += -padding * 2

    ### if text as it is fits width, then return earlier
    if not font.size(text)[0] > max_width:
        return text

    ### define the ellipsis text
    ellipsis = "\N{horizontal ellipsis}"

    ### if not even the ellipsis text fits the max width,
    ### we raise an error to indicate such.
    if font.size(ellipsis)[0] > max_width:
        raise ValueError("max_width defined is too small.")

    ### concatenate the ellipsis with the text according
    ### to the ommit_direction and also define the index
    ### from which we will repeatedly remove characters
    ### when making the text shorter

    if ommit_direction == "left":
        text = ellipsis + text
        pop_index = 1

    elif ommit_direction == "right":
        text = text + ellipsis
        pop_index = -2

    else:

        raise RuntimeError("This 'else' clause should never be reached")

    ### define a list of the characters
    char_list = list(text)

    ### iterate over the list, removing characters closer
    ### to the ellipsis; the number of iterations is equal
    ### to the number of characters minus the ellipsis

    number_of_iterations = len(text) - 1

    for _ in range(number_of_iterations):

        ## pop the char nearest to the ellipsis and
        ## join the text together

        char_list.pop(pop_index)
        text = "".join(char_list)

        ## if font width of the resulting text fits the
        ## max_width, we can leave the for loop
        if font.size(text)[0] <= max_width:
            break

    ### we finally return the text
    return text
Return optimal text to fit max_width passed.
nodezator/textman/render.py