nb icon indicating copy to clipboard operation
nb copied to clipboard

cd in folder

Open JoFo-IT opened this issue 1 year ago • 1 comments

When working inside the nb shell, I’d like to navigate into subfolders without having to specify the full path every time.

For example, if there is a folder called 1, I would expect this to work:

cd 1

and then be able to create new notes or files inside that folder.

However, currently this doesn’t seem to work – I have to reference the full path instead. Is there a recommended way to change directories or navigate easily within the nb shell, or am I missing a specific syntax?

JoFo-IT avatar Nov 21 '25 15:11 JoFo-IT

I discovered a solution through a plugin.

#!/usr/bin/env bash
###############################################################################
# cd.nb-plugin
###############################################################################

_subcommands add "cd"

_subcommands describe "cd" <<'HEREDOC'
Usage:
  nb cd [FOLDER]
Description:
  Change the current notebook location relative to NB_DIR.
  Handles ".", "..", and "/" (goes to the notebook's root folder dynamically).
  Calls _use with the notebook-relative path and prints the full path.
HEREDOC

_cd() {
  local NEW_PATH REL_PATH ARG ROOT_SUBDIR

  # Safety checks
  : "${NB_DIR:?Error: NB_DIR is not set!}"
  : "${NB_NOTEBOOK_PATH:?Error: NB_NOTEBOOK_PATH is not set!}"

  # Get the notebook-relative path (strip base NB_DIR)
  REL_PATH="${NB_NOTEBOOK_PATH#$NB_DIR/}"

  # Determine the top-level (root) folder name dynamically
  ROOT_SUBDIR="${REL_PATH%%/*}"

  # Optional user argument
  ARG="$1"

  if [ -n "$ARG" ]; then
    case "$ARG" in
      /)
        # Go back to the notebook’s root folder (dynamic)
        REL_PATH="$ROOT_SUBDIR"
        ;;
      *)
        # Append folder argument
        REL_PATH="${REL_PATH%/}/$ARG"
        ;;
    esac
  fi

  # Normalize (resolves '.', '..', etc.)
  NEW_PATH="$(realpath -m "$NB_DIR/$REL_PATH")"

  # Update NB_NOTEBOOK_PATH
  NB_NOTEBOOK_PATH="$NEW_PATH"

  # Determine relative path for _use
  REL_PATH="${NB_NOTEBOOK_PATH#$NB_DIR/}"

  # Call _use with the notebook-relative path
  _use "$REL_PATH"

  # Print full path for feedback
  printf "%s\n" "$NB_NOTEBOOK_PATH"
}

``

JoFo-IT avatar Nov 22 '25 10:11 JoFo-IT