Skip to content

Instantly share code, notes, and snippets.

@hamelin
Last active December 23, 2021 16:45
Show Gist options
  • Save hamelin/a071b908846eee314d915d5fabee97ed to your computer and use it in GitHub Desktop.
Save hamelin/a071b908846eee314d915d5fabee97ed to your computer and use it in GitHub Desktop.
Configuration to get Jupyter Lab's editor to trim whitespace at the end of each line when it saves a file.
# 1. Run: jupyter lab --generate-config
# 2. Edit $PATH/.jupyter/jupyter-lab-config.py, add the following at the end.
#
# In Jupyterhub, one needs to restart their "server" to get such config changes to take.
def strip_ws(t):
return '\n'.join([i.rstrip() for i in t.split('\n')])
def scrub_output_pre_save(model=None, **kwargs):
# """strip trailing space before saving"""
if model['type'] == 'notebook':
if model['content']['nbformat'] != 4:
import sys
print("skipping WS stripping since `nbformat` != 4", file=sys.stderr)
return
for cell in model['content']['cells']:
if cell['cell_type'] == 'code':
cell['source'] = strip_ws(cell['source'])
elif model['type'] == 'file':
if model['format'] == 'text':
model['content'] = strip_ws(model['content'])
c.ContentsManager.pre_save_hook = scrub_output_pre_save
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment