Skip to content

Instantly share code, notes, and snippets.

@rldotai
Last active February 7, 2021 04:42
Show Gist options
  • Save rldotai/0c423571ce5ec304d29ef346f096aa74 to your computer and use it in GitHub Desktop.
Save rldotai/0c423571ce5ec304d29ef346f096aa74 to your computer and use it in GitHub Desktop.
Get the number of columns in a Jupyter notebook output cell, from within the notebook itself.
%%html
<canvas id="canvas"></canvas>
<script>
/* A function that reports the width of a Jupyter notebook cells */
function reportWidth() {
/* Get an output area element */
let el = document.querySelector("div.output_subarea.output_text.output_stream.output_stdout > pre");
/* Determine the width of the output area, in pixels */
let output_width = el.clientWidth;
/* Identify the font size and family */
let font_size = window.getComputedStyle(el, null).getPropertyValue('font-size');
let font_family = window.getComputedStyle(el, null).getPropertyValue('font-family');
/* Create canvas+context and set font */
let can = document.getElementById('canvas');
let ctx = can.getContext('2d');
ctx.font = font_size + ' ' + font_family;
/* Measure the width of a character */
let char_width = ctx.measureText('M').width;
console.log("Font:", ctx.font);
console.log("Character width:", char_width);
console.log("Output width:", output_width);
console.log("Number of columns:", output_width/char_width);
/* Execute a statement to save the number of columns in an output cell */
IPython.notebook.kernel.execute("__output_cols=" + Math.floor(output_width/char_width));
}
reportWidth();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment