zimfw / magicmace

A prompt theme inspired by xero's and eriner's themes.
MIT License
4 stars 0 forks source link

How to achieve short working directory #2

Closed KiteAB closed 4 years ago

KiteAB commented 4 years ago

As the title. I want to apply short working directory to gitster

KiteAB commented 4 years ago

Like from this: ~/Documents/GitHub To this: ~/D/GitHub And apply it to my gitster theme

ericbn commented 4 years ago

Hi @KiteAB, this is the code that shortens the pwd:

  local current_dir=${PWD/#${HOME}/~}"
  if [[ ${current_dir} != '~' ]]; then
    current_dir="${${(@j:/:M)${(@s:/:)current_dir:h}#?}%/}/${current_dir:t}"
  fi

The longest line is doing most of the work:

  1. /${current_dir:t}: keep the tail directory (last directory in the path)
  2. ${(@s:/:)current_dir:h}: split the remaining directories into an array
  3. ${(@j:/:M)...#?}: join the first letter of the array elements
  4. ${...%/}: remove extra slash in case we're in the root directory

You can apply the same code to your custom prompt. If you want to use that with gitster, it will look like:

  local git_root current_dir
  if git_root=$(command git rev-parse --show-toplevel 2>/dev/null); then
    current_dir="${PWD#${git_root:h}/}"
  else
    current_dir=${PWD/#${HOME}/~}"
  fi
  if [[ ${current_dir} != '~' ]]; then
    current_dir="${${(@j:/:M)${(@s:/:)current_dir:h}#?}%/}/${current_dir:t}"
  fi
  print -n "%F{white}${current_dir}"
KiteAB commented 4 years ago

It's working! But there are still some small problems: In git repositories, It's look's not nice.

KiteAB commented 4 years ago

After short working directory: Before short working directory:

KiteAB commented 4 years ago

Pleasse remember me @ericbn

ericbn commented 4 years ago

@KiteAB, it's been only 14 hours since your reply, and now you sound demanding. It's not fair to address me or any other person who puts their free time in trying to build a great piece of software, in this manner.

KiteAB commented 4 years ago

@KiteAB, it's been only 14 hours since your reply, and now you sound demanding. It's not fair to address me or any other person who puts their free time in trying to build a great piece of software, in this manner.

Oh, sorry. Sorry to bother you, my problem has been basically solved, thank you

ericbn commented 4 years ago

@KiteAB, you might want to use this with gitster. It will keep the git root directory unshortened too, which I think goes well with the spirit of this prompt:

  local git_root current_dir
  if git_root=$(command git rev-parse --show-toplevel 2>/dev/null); then
    current_dir="${PWD#${git_root:h}/}"
  else
    current_dir=${(%):-%~}
  fi
  local -r dirs=("${(@s:/:)current_dir}")
  if (( ${#dirs} > 2 )); then
    current_dir="${dirs[1]}/${(@j:/:M)dirs[2,-2]#?}/${dirs[-1]}"
  fi
  print -n "%F{white}${current_dir}"
KiteAB commented 4 years ago

I am surprised that you can give the final answer, thank you very much!