def nb2lang(nb):
    """ Detect language of notebook `nb`

    Parameters
    ----------
    nb : dict
        Notebook dictionary.

    Returns
    -------
    lang : str
        Detected language.
    """
    metadata = nb['metadata']
    if 'kernelspec' in metadata:
        # Probably a Jupyter notebook
        return metadata['kernelspec']['name']
    # Guess from main_language
    return metadata['jupytext'].get('main_language', 'R')