Line Wrapping in Collaboratory Google results

Normally on my own machine, I put this the following css snippit in the ~/.jupyter/custom/custom.css file.

pre {
  white-space: pre-wrap;
}

But, the above does not work for google colab: I tried creating a file /usr/local/share/jupyter/custom/custom.css, but this didn’t work.

Instead, put this in the first cell of your notebook.

from IPython.display import HTML, display

def set_css():
  display(HTML('''
  <style>
    pre {
        white-space: pre-wrap;
    }
  </style>
  '''))
get_ipython().events.register('pre_run_cell', set_css)

Explanation: As described in Google Colab advanced output , get_ipython().events.register('pre_run_cell', <function name>)

defines an execution hook that loads it [our custom set_css() function in our
case] automatically each time you execute a cell

My interpretation is that you need to specify 'pre_run_cell' as the first argument in the events.register, which tells the events.register function that you wish to run your custom set_css() function before the contents of the cell is executed.

This answer was inspired by How to import CSS file into Google Colab notebook (Python3)

Leave a Comment