From 4febd31dbab525556ac10b94cf8a787026389669 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adam=20Harald=20J=C3=B8rgensen?= <58829763+adamjoer@users.noreply.github.com> Date: Thu, 2 Nov 2023 19:08:24 +0100 Subject: [PATCH] Shell: Shorten prompt path if integer is provided with "\w" option --- Base/usr/share/man/man7/Shell-vars.md | 2 +- Userland/Shell/Shell.cpp | 27 +++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/Base/usr/share/man/man7/Shell-vars.md b/Base/usr/share/man/man7/Shell-vars.md index 94209c89c4..f56517c5a0 100644 --- a/Base/usr/share/man/man7/Shell-vars.md +++ b/Base/usr/share/man/man7/Shell-vars.md @@ -61,7 +61,7 @@ The value of this variable is used to generate a prompt, the following escape se - `\\h`: the current hostname - `\\p`: the string '$' (or '#' if the user is 'root') - `\\u`: the current username -- `\\w`: a collapsed path (relative to home) to the current directory +- `\\w`: a collapsed path (relative to home) to the current directory. If an integer follows the `\\`, it specifies the number of trailing components of the path to show - `\\X`: reset style (foreground and background color, etc) - `\\t`: current time in the 24-hour format HH:MM:SS - `\\T`: current time in the 12-hour format HH:MM diff --git a/Userland/Shell/Shell.cpp b/Userland/Shell/Shell.cpp index 5af8cf3a5a..b7ff2250e6 100644 --- a/Userland/Shell/Shell.cpp +++ b/Userland/Shell/Shell.cpp @@ -127,6 +127,33 @@ DeprecatedString Shell::prompt() const builder.append(cwd); } + } else if (auto const number_string = lexer.consume_while(is_ascii_digit); !number_string.is_empty()) { + if (lexer.is_eof() || lexer.consume() != 'w') + continue; + + auto const max_component_count = number_string.to_uint().value(); + + DeprecatedString const home_path = getenv("HOME"); + + auto const should_collapse_path = cwd.starts_with(home_path); + auto const path = should_collapse_path ? cwd.substring_view(home_path.length(), cwd.length() - home_path.length()) + : cwd.view(); + auto const parts = path.split_view('/'); + + auto const start_index = (max_component_count < parts.size()) ? parts.size() - max_component_count : 0; + if (start_index == 0) { + if (should_collapse_path) + builder.append('~'); + builder.append(path); + continue; + } + + for (auto i = start_index; i < parts.size(); ++i) { + if (i != start_index) + builder.append('/'); + builder.append(parts[i]); + } + } else if (lexer.consume_specific('p')) { builder.append(uid == 0 ? '#' : '$');