def completions_sorting_key(word):
    """key for sorting completions

    This does several things:

    - Demote any completions starting with underscores to the end
    - Insert any %magic and %%cellmagic completions in the alphabetical order
      by their name
    """
    prio1, prio2 = 0, 0
    if word.startswith('__'):
        prio1 = 2
    elif word.startswith('_'):
        prio1 = 1
    if word.endswith('='):
        prio1 = -1
    if word.startswith('%%'):
        if not '%' in word[2:]:
            word = word[2:]
            prio2 = 2
    elif word.startswith('%'):
        if not '%' in word[1:]:
            word = word[1:]
            prio2 = 1
    return prio1, word, prio2
