Oh my posh windows terminal

Cover image for How to Set up the Windows terminal with Powershell and Oh My Posh

Hello everyone! Today I gonna show you how to set up the Windows terminal to look great.

✨ Content

  1. Install the Windows terminal
  2. Install Oh My Posh
  3. Install fonts
  4. Install icons
  5. Select the prompt
  6. Set up the terminal background

⚙ Requirements

  • Windows ≥ 10
  • Oh My Posh
  • Nerd fonts

📚 GitHib Repo

  • https://github.com/slydragonn/dotfiles

1. Install Windows Terminal

To install this terminal you should have Windows 10 or 11. It’s very easy, You direct to the Microsoft store and search Windows terminal and install this option:

windows terminal

Or install the Terminal via this link: https://apps.microsoft.com/store/detail/windows-terminal/9N0DX20HK701

2. Install Oh My Posh

You can install Oh My Posh via Winget, scoop, or manually with PowerShell commands.

  • ohmyposh.dev

I installed it via Winget:

winget install JanDeDobbeleer.OhMyPosh -s winget

Enter fullscreen mode

Exit fullscreen mode

3. Install fonts

This part is important because the fonts are giving the icons for their own terminal.

  • NerdFonts

I installed the Hack Nerd Fonts:

Nerd fonts

Then, you should extract the font files and copy them and move to this place.

Note: Search fonts settings, then drag and drop the files and press install fonts.

font install

And Select in the Terminal the Hack Nerd Fonts:

select fonts from terminal

4. Install Icons

For you can see the icons in your terminal, you should install the next repository:

  • devblackops/Terminal-Icons

To install:

Install-Module -Name Terminal-Icons -Repository PSGallery

Enter fullscreen mode

Exit fullscreen mode

Usage: Copy this code into Microsoft.PowerShell_profile.ps1 file on the route ⇒ C:\Users\YOUR_USER_NAME\OneDrive\Documentos\PowerShell

Import-Module -Name Terminal-Icons

Enter fullscreen mode

Exit fullscreen mode

and your terminal looks like this:

terminal icons

5. Select the prompt

Oh My Posh has many themes for the terminal, I like the half-life theme and to select this theme you write inside the config file the next code:

# C:\Users\YOUR_USER_NAME\OneDrive\Documentos\PowerShell\Microsoft.PowerShell_profile.ps1
oh-my-posh init pwsh --config "$env:POSH_THEMES_PATH\half-life.omp.json" | Invoke-Expression

Enter fullscreen mode

Exit fullscreen mode

And this is the result:

terminal prompt

6. Set up the terminal background

Go to the terminal settings and activate the option “Use the acrylic material in the tab row” ubicated in the appearance section and save.

terminal config

Then go to predeterminate values/appearance and in the transparency section active the material acrylic, play with the opacity, and save:

terminal transparency

And the result looks like this:

terminal style

This is what the config file looks like:

oh-my-posh init pwsh --config "$env:POSH_THEMES_PATH\half-life.omp.json" | Invoke-Expression

Import-Module -Name Terminal-Icons

Enter fullscreen mode

Exit fullscreen mode

And that’s all, Thank you for reading, and see you later :)

Последнее время стало модным использовать продвинутую командную строку в PowerShell или bash/zsh. В этой статье я расскажу, что нужно сделать в PowerShell, WSL, Windows Terminal и VS Code, чтобы кастомизировать командную строку и воспользоваться всеми её преимуществами.

assets/images/oh-my-posh/1.png

Краткий план действий:

  • Установка шрифта Nerd
  • Установка и настройка Oh My Posh для PowerShell
  • Установка и настройка Oh My Posh для WSL
  • Настройка Windows Terminal для правильного отображения глифов
  • Настройка Windows VS Code для правильного отображения глифов

Из официальной документации я мало что понял. Пришлось разбираться самому. Поэтому сейчас я по порядку опишу путь, который пришлось пройти мне, чтобы заставить всё работать как надо.

Установка шрифта Nerd

assets/images/oh-my-posh/5.png

На картинке выше, показаны некоторые варианты оформления (тем) командной строки. На самом деле таких тем много, и вы можете их изменять и создавать свои. Как вы видите, почти все варианты содержат глифы (графические символы). Если шрифт, который используется в терминале, не содержит соответствующие глифы, в командной строке могут появиться символы замены, например квадрат — ▯ или знак вопроса �. Чтобы в терминале отображались все глифы, нужно сначала установить шрифт Nerd с сайта проекта https://www.nerdfonts.com/.

Nerd Fonts улучшает предназначенные для разработчиков шрифты с большим количеством глифов (значков). В частности, чтобы добавить большое количество дополнительных глифов из популярных «культовых шрифтов», таких как Font Awesome, Devicons, Octicons и других.

Посмотрев несколько шрифтов, я остановил свой выбор на Caskaydia Cove Nerd Font.

Все шрифты можно посмотреть по ссылке https://www.nerdfonts.com/font-downloads.

Скачав нужный шрифт, нужно его установить. Заходим в архив, выбираем нужный шрифт и открываем его.

assets/images/oh-my-posh/3.png

А затем, в открывшемся окне, нажимаем кнопку Install

assets/images/oh-my-posh/4.png

Шрифт установлен, можно переходить к следующему шагу — установке Oh My Posh.

Установка и настройка Oh My Posh для PowerShell

Как сказано в официальной документации, Oh My Posh — это настраиваемый механизм командной строки, для любой оболочки, которая имеет возможность настроить командную строку с помощью функции или переменной. Чтобы воспользоваться этим механизмом в PowerShell, нужно установить и импортировать соответствующий модуль.

Но это может не получится, если параметр ExecutionPolicy в PowerShell установлен в Restricted или иное значение, которое не позволяет запускать удалённые скрипты. Что бы проверить текущие политики, выполните команду Get-ExecutionPolicy. Чтобы их изменить, запустите PowerShell от имени администратора и выполните команду и нажмите Y, а затем Enter для подтверждения.

Set-ExecutionPolicy RemoteSigned

Это позволит вам установить нужный модуль.

assets/images/oh-my-posh/6.png

ВНИМАНИЕ: После изменения ExecutionPolicy закройте окно PowerShell, которое вы открывали с повышенными привелегиями и откройте новое, с правами обычного пользователя.

Чтобы установить модуль Oh My Posh выполните следующую команду.

Install-Module oh-my-posh -Scope CurrentUser

Если пакетный менеджер NuGet ещё не установлен, то PowerShell запросит разрешение на его установку. Введите Y и нажмите Enter.

Далее вас предупредят, что вы собираетесь ставить модуль из недоверенного репозитория PSGallery. На самом деле всё нормально. Просто изначально все репозитории считаются недоверенными. Можете смоело продолжать установку введя Y и нажав Enter.

assets/images/oh-my-posh/7.png

Обновите профиль PowerShell, отредактировав файл Microsoft.PowerShell_profile.ps1. Самым простым способом открытия этого файла, явялется выполнение следующей команды.

Если файла не существует, то система предложет вам его создать. Нажмите Yes в диалоговом окне.

assets/images/oh-my-posh/8.png

Добавьте следующий фрагмент в конце файла. Вместо jandedobbeleer можете написать название другой темы. Я для себя выбрал именну эту.

Import-Module oh-my-posh
Set-PoshPrompt -Theme jandedobbeleer

Сохраните и закройте файл. Теперь каждый новый экземпляр PowerShell будет запущен с импортом Oh My Posh и установкой темы командной строки.

Запустите новый экземляр PowerShell. При первом запуске вы можете увидеть процесс импорта установленного ранее модуля Oh My Posh. Он выполниться один раз. Все последующие запуски PowerShell будут проходить как обычно.

assets/images/oh-my-posh/9.png

После запуска вы увидите обновлённую командную строку, как показано на картинке ниже. Обратите внимание, что не все символы отображаются корректно. Это связано с тем, что в терминале PowerShell сейчас используется шрифт, который не поддерживает глифы.

assets/images/oh-my-posh/10.png

Зайдите в настройки терминала PowerShell и выберите шрифт с поддержкой глифов, который вы установили ранее. Или установите его сейчас, если вы пропустили этот шаг.

Как установить шрифт с поддержкой глифов, смотри в начале статьи.

Как только вы установите нужный шрифт, вы сразу же увидите правильное отображение командной строки.

assets/images/oh-my-posh/12.png

Установка и настройка Oh My Posh для WSL

Если вы используете Windows 10 версии 2004 и выше (Build 19041 и выше) или Windows 11, и у вас ещё не установлен WSL, но вы хотите его установить, то запустите команду wsl --install в терминале powershell с повышенными привилегиями, а после установки WSL перезапустите Windows. После перезапуска, установка продолжится. Более подробные сведения об установке и настройке WSL смотрите в моей статье “Установка и настройка WSL” (comming soon...)

Для установки Oh My Posh в Linux (WSL) нам потребуется пакетный менеджер Homebrew. Поэтому сначала запустите WSL и установите там Homebrew, выполнив следующую команду и следуйте инструкциям в окне терминала.

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

После того, как Homebrew будет установлен, нужно выполнить неколько команд, чтобы добавить Homebrew в PATH и в профиль командной оболочки bash.

test -d ~/.linuxbrew && eval "$(~/.linuxbrew/bin/brew shellenv)"
test -d /home/linuxbrew/.linuxbrew && eval "$(/home/linuxbrew/.linuxbrew/bin/brew shellenv)"
test -r ~/.bash_profile && echo "eval \"\$($(brew --prefix)/bin/brew shellenv)\"" >> ~/.bash_profile
echo "eval \"\$($(brew --prefix)/bin/brew shellenv)\"" >> ~/.profile

После установки и настройки Homebrew, можно приступать к установке Oh My Posh. Выполните следубщие команды.

brew tap jandedobbeleer/oh-my-posh
brew install oh-my-posh

Установите пакет unzip. Он понадобится для распаковки архива с темами. Этот шаг можно пропустить, если вы скачаете тему самостоятельно, извлекёте из архива файл с темой для Oh My Posh и положите его в домашнюю директорию пользователя. Иначе, выполните нижеследующие команды.

Теперь нужно скачать и распаковать темы.

mkdir -p $(brew --prefix)/oh-my-posh/themes
wget https://github.com/JanDeDobbeleer/oh-my-posh/releases/latest/download/themes.zip -O $(brew --prefix)/oh-my-posh/themes/themes.zip
unzip $(brew --prefix)/oh-my-posh/themes/themes.zip -d $(brew --prefix)/oh-my-posh/themes
chmod u+rw $(brew --prefix)/oh-my-posh/themes/*.json
rm $(brew --prefix)/oh-my-posh/themes/themes.zip

Скопируйте файл темы в домашнюю директорию.

cp $(brew --prefix)/oh-my-posh/themes/jandedobbeleer.omp.json ~/jandedobbeleer.omp.json

А затем запустите oh-my-posh.

test -e ~/jandedobbeleer.omp.json && eval "$(oh-my-posh --init --shell bash --config ~/jandedobbeleer.omp.json)"

Вы увидите, что командная строка изменилась. Если она отображается не правильно, то измените шрифт в настройках вашего терминила, как говорилось ранее.

assets/images/oh-my-posh/23.png

На этом установка и настройка Oh My Posh для WSL завершена.

Настройка Windows Terminal для правильного отображения глифов

После запуска Windows Terminal вам нужно будет тольк сменить шрифт, иначе командная строка будет отображаться без глифов.

assets/images/oh-my-posh/16.png

Чтобы это исправить, зайдите в настройки Windows Terminal, выберите профиль по умолчанию и на вкладке Appearance установите нужный шрифт. Затем нажмите Save и откройте новое окно терминала.

assets/images/oh-my-posh/17.png

На этот раз командная строка будет отображать глифы, но есть одна проблема. При открытии WSL-терминала, первая командная строка отображается с дефектом. В ней присутствуют пропуски. Я не понял почему это происходит. Если нажать Enter, то следующая строка отобразиться нормально.

assets/images/oh-my-posh/18.png

Я не придумал ничего лучше, чем добавить команду очистки экрана в файл .profile, чтобы она выполнялась каждый раз, при запуске сессии. Вы тоже можете это сделать, выполнив следующую команду.

echo "clear" >> ~/.profile 

Теперь, если переоткрыть терминал, то всё будет выглядеть как надо.

assets/images/oh-my-posh/19.png

И на этом часть по настройке Windows Terminal завершена. Посмотрите другю мою статью, где я описываю, как настроить более приятный вид Windows Terminal (comming soon...).

Настройка VS Code для правильного отображения глифов

Если вы откроете VS Code, и в нём откроете Terminal, то вы увидите, что глифы в нём тоже отображатся неправильно. Всё дело в настройках шрифтов.

assets/images/oh-my-posh/24.png

Зайдите в настройки, выберите Terminal, пролистайте до настройки Integrated: Font Family и введите название своего шрифта. В моём случае это CaskaydiaCove NF. Полное название настройки terminal.integrated.fontFamily, можете вбить её в строку поиска настроек, для быстрого перехода к ней.

assets/images/oh-my-posh/20.png

Если вы используете плагин Remote - WSL в VS Code, то возможно вам пригодится ещё один совет. Дело в том, что когда вы откроете новую сессию в WSL в VS Code, то заметите, что там ничего не поменялось. VS Code, при запуске bash в WSL, не читает данные из файла .profile, которые мы туда поместили.

assets/images/oh-my-posh/21.png

Чтобы это исправить, можно ввести команду

Параметр -l (согласно справочной странице) заставляет «bash действовать так, как если бы он был вызван как оболочка входа в систему». Оболочки входа читают определенные файлы инициализации из вашего домашнего каталога, такие как .profile.

Но чтобы не делать это каждый раз вручную, давайте изменим конфигурацию VS Code.

К уже имеющимся настройкам, если они есть, добавьте следующие.

assets/images/oh-my-posh/22.png

"terminal.integrated.defaultProfile.linux": "bash",
    "terminal.integrated.profiles.linux": {
        "bash": {
            "path": "bash",
            "args": [
                "-l"
            ]
        }
    }

Сохраните и перезапустите WSL-сессию. На этот раз у Вас всё должно отображаться правильно.

Вот и всё, чем я хотел поделиться в этой статье. Оставльяйте свои комментарии и отзывы. Всем мира и добра!

I’ve long blogged about my love of setting up a nice terminal, getting the prompt just right, setting my colors, fonts, glyphs, and more. Here’s some of my posts.

  • How to make a pretty prompt in Windows Terminal with Powerline, Nerd Fonts, Cascadia Code, WSL, and oh-my-posh
  • Patching the new Cascadia Code to include Powerline Glyphs and other Nerd Fonts for the Windows Terminal
  • What’s the difference between a console, a terminal, and a shell?
  • Taking your PowerShell prompt to the next level with Windows Terminal and Oh my Posh 3

I want to take a moment to update my pretty prompt post with a little more detail and a more complex PowerShell $PROFILE, due to some changes in Oh My Posh, PowerShell, and the Windows Terminal. I doubt that this post is perfect and I’m sure there’s stuff here that is a little extra. But I like it, and this post will serve as my «setting up a new machine» post until I get around to writing a script to do all this for me in one line.

I love my prompt.

A pretty prompt in Terminal with Oh My Posh and a lot of Colors

Let’s get you set up!

Get PowerShell

I don’t mean Windows PowerShell (that’s «classic» now) I mean the .NET Core-powered cross-platform PowerShell. There’s a LOT of ways to get it but I’m a Store person usually so I can get PowerShell (and it’ll auto update) from the Microsoft Store or just «winget install Microsoft.PowerShell» from the command line with winget.

Get Windows Terminal and set a default Shell

Get Windows Terminal if you don’t already have it, you can get Windows Terminal free from the Store. If you don’t have access to the Microsoft Store, the builds are published on the GitHub releases page. It comes with a lovely font called Cascadia Code…but…

Now that you have Windows Terminal, you’ll notice that it knows that you have PowerShell installed and will add it to your Windows Terminal dropdown menu! You can set PowerShell as your default Profile — that’s the one you’ll get by default when you make a new Tab — in settings:

Set your Default Profile to PowerShell

Upgrade your Terminal/Console Fonts

I like fonts with lots of Glyphs so I also download and Install Caskaydia Cove Nerd Font Complete. This is the same Cascadia Code font but MODIFIED to include hundreds of special characters that you can use to make your prompt cooler.

IMPORTANT NOTE: The string literal name of this font for use in settings or VS Code is «CaskaydiaCove NF». If you’re using Cascadia Code, there are different strings for each. The NUMBER ONE question I get is ‘why don’t my glyphs/fonts show up right in Windows Terminal/VS Code?’ and the answer is almost always «you’re using the wrong font string.» It’s usually either an extra space or a missing space, so don’t be afraid to double check.

Remember that Windows Terminal has a lovely Settings UI but you can always click «open JSON file» to manage the settings.json as text if you prefer. Here’s mine. Yours will be different and you should customize it! The Windows Terminal documentation is fantastic. Again, see how PowerShell is in BOLD? That’s because it’s my default.

Lots of Windows Terminal Profiles

Now, let’s add a little…spice…

Add «Oh My Posh» to your Shell

Oh My Posh has amazing docs so check them out. Do note that some stuff has changed, especially from v2 to v3.

EXCITING NOTE: Oh My Posh is portable and works on any shell, so I use it on both my «Pwsh» (PowerShell) in Windows and my Bash shells on WSL running Ubuntu.

You can install Oh My Posh with with PowerShell’s «Install-Module» or with the platform-specific install instructions. I used the latter, which is somewhat new, but it’s tomato/tomato, so use what works for you.

Again, read the docs but the idea on Windows is basically this (or get it from GitHub):

winget install JanDeDobbeleer.OhMyPosh
# restart shell to reload PATH

Then edit $PROFILE and add the following line, remembering at this point that oh-my-posh is an executable on the PATH.

oh-my-posh --init --shell pwsh --config ~/jandedobbeleer.omp.json | Invoke-Expression

I have changed my Oh My Posh from Jan’s default to include my own stuff, and I keep my latest up in a GitHub Gist and also in my DropBox/OneDrive so it’s always syncing to all my machines. Mine is this, after I download from my gist.

oh-my-posh --init --shell pwsh --config D:/Dropbox/ohmyposhv3-2.json | Invoke-Expression

Yours will vary. Again, read the docs and experiment! Once added, reload your profile for the changes to take effect, or restart your shell.

. $PROFILE

That .json file is filled with «segments» that are documented on the Oh My Posh site in a lot of detail. Overwhelming detail. You can add your computer’s battery, your Azure Subscription, the dotnet or node version of your current folder, really anything. Even your Spotify songs. I’m going to make one that show my Blood Sugar.

Go explore Oh My Posh Themes and then modify them with your own additional Segments.

Again, note that your fonts will need the right glyphs or it will look weird.

Here’s a GOOD prompt:

This prompt has nice glyphs

Here’s a BAD prompt with an issue!

This prompt has weird squares

Why is it wrong? Either the .json file that is your config has been saved wrong or corrupted the Unicode Glyphs, or you’ve got a font that doesn’t have those glyphs.

Re-assert your Git segment in Oh My Posh

Some folks want full git info, status, added, modified, untracked, etc and others just want the current git branch. Check the Git segment and the Posh Git segment to make sure you are getting the performance AND information you need.

I needed to turn on «display_stash_count» and «display_upstream_icon» in my config json, like this:

{
"type": "git",
"style": "powerline",
"powerline_symbol": "",
"invert_powerline": false,
"foreground": "#193549",
"background": "#fffb38",
"leading_diamond": "",
"trailing_diamond": "",
"properties": {
"display_status": true,
"display_stash_count": true,
"display_upstream_icon": true
}
},

Again, this is all optional and affect performance slightly, but be aware of these properties. I believe I have these set the right way I want them in my public gist. Here is me moving around my source code with «z» in stead of cd, but note the prompt changes.

My prompt shows my Git branch

Turn your PowerShell directories up to 11 with Terminal-Icons

Is your prompt not extra enough? That’s because your directory listing needs color AND cool icons!

Install-Module -Name Terminal-Icons -Repository PSGallery

And then add one line to my $profile (edit with «code $profile»):

Import-Module -Name Terminal-Icons

Sweet!

Cool Icons and color in DIR

How far is too far?

At this point you’re basically done, but I also LOVE PSReadLine. It’s great generally but also nice for bash and Emacs types who are moving to PowerShell or use PowerShell for work.

I’ve added features like «ctrl shift b» at the command line will run «dotnet build.» Why? Because I can and because it’s muscle memory so I’m making my prompt work for me.

You can also add Predictive Autocomplete to your prompt if you like but I’ll leave that as an exercise to the reader! My PowerShell profile is on a public gist, and while it’s not perfect and likely has issues, it works for me!

Enjoy! Thanks to the Windows Terminal Team and the always lovely Jan De Dobbeleer from Oh My Posh, as well as Brandon Olin from Terminal Icons.


Check out our Sponsor! YugabyteDB is a distributed SQL database designed for resilience and scale. It is 100% open source, PostgreSQL-compatible, enterprise-grade, and runs across all clouds. Sign up and get a free t-shirt!

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

About   Newsletter

Hosting By

Setting up a decent looking Windows Terminal with Oh-my-Posh that works with WSL and integrate it in VSCode and IntelliJ

This is a briefly summary of what I did to set up my Windows Terminal for Powershell on the Windows side and Zsh on the WSL(Ubuntu) side and integrate it in VSCode and IntelliJ.

       

Powershell and Windows Terminal

Let’s begin by setting up powershell and the Windows Terminal.

Installation of required packages

Optional: Upgrading PowerShellGet and PackageManagement

Fell free to skip this part. I just wanted to make sure everything is up to date.

  1. Run Powershell as administrator

  2. Install the newest NuGet version

    > Install-PackageProvider Nuget -Force
  3. Install the newest version of PowerShellGet and PackageManagement

    > Install-Module -Name PowerShellGet -Force
    > Install-Module -Name PackageManagement -Force
  4. Remove the previous versions by deleting the respective folders in the installation path. The following command will show all available powershell packages with their version and their installation path:

    > Get-Module -ListAvailable

Install Terminal-Icons

Install Terminal-Icons via PowerShellGet to get some nice looking icons for the ls output:

> Install-Module -Name Terminal-Icons

Install posh-git

Install posh-git via PowerShellGet for git command autocompletion:

> Install-Module -Name posh-git

Install Oh-my-Posh

You can easily install Oh-my-Posh via winget:

> winget install JanDeDobbeleer.OhMyPosh

For other installation methods check out the docs.

Install a Powerline Font

Install a powerline font, so that glyphs used in oh-my-posh themes are rendered correctly. Nerdfonts has a decent selection of fonts. I am using the Caskaydia Cove Nerd Font and Meslo Font but feel free to choose what suits your needs.

Setup

Now that we have installed all required packages we can start with the setup.

Oh-my-Posh Theme

You can use one of the default themes that you can install with

create your own theme (take a look in the documentation) or use my theme. Make sure to provide the path to your theme in your powershell profile:

Powershell Profile

Open the Powershell Profile for the current user or create one under ~\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 if it does not exist and add the following:

# Importing Powershell Packages to the current session
Import-Module PackageManagement
Import-Module PowerShellGet
Import-Module Terminal-Icons
Import-Module posh-git

# Oh-my-posh Setup
oh-my-posh --init --shell pwsh --config "path to oh-my-posh theme" | Invoke-Expression

# Tweaked PSReadLine Colors to fit my color scheme
# Feel free to change it :)
Set-PSReadLineOption -Colors @{
  Command  = 'Green'
  Comment  = 'DarkGray'
  Variable = 'Magenta'
  Keyword  = 'Magenta'
}

Windows Terminal Settings

Add the following json snippets to the Windows Terminal settings to mimic my settings. Of course you can change everything to your needs.

Hint: Do not copy the comments, cause json don’t support them. I just added them for explanation purposes 🙃

// Set powershell as default shell
{
	"defaultProfile": "Enter guid of Windows Powershell to set Powershell as default shell"
}
// Set default appereance
{
	"profiles": {
		"defaults": {
			"acrylicOpacity": 0.90000000000000002,
			"colorScheme": "ColorOne",
			"font": {
				"face": "CaskaydiaCove NF",
				"size": 12,
				"weight": "normal"
			},
			"useAcrylic": false
		}
	}
}
// Add color scheme
{
	"schemes": [
		{
			"background": "#282C34",
			"black": "#282C34",
			"blue": "#0078FF",
			"brightBlack": "#5A6374",
			"brightBlue": "#0078FF",
			"brightCyan": "#4FB2FF",
			"brightGreen": "#39FA73",
			"brightPurple": "#A140FC",
			"brightRed": "#ED3E4E",
			"brightWhite": "#F2F2F2",
			"brightYellow": "#F1F139",
			"cursorColor": "#FFFFFF",
			"cyan": "#4FB2FF",
			"foreground": "#F2F2F2",
			"green": "#39FA73",
			"name": "ColorOne",
			"purple": "#A140FC",
			"red": "#ED3E4E",
			"selectionBackground": "#FFFFFF",
			"white": "#F2F2F2",
			"yellow": "#F1F139"
		}
	]
}

WSL

Now that we have set up powershell and the Windows Terminal we can set up zsh and oh-my-posh for WSL.
PS: I am using Ubuntu, but the steps should be replicatible when using other distros.

Installation of required packages

Install Zsh

Install Zsh Syntax Highlighting

> git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ~/.zsh/zsh-syntax-highlighting

Install Oh-my-Posh

Download Oh-my-Posh from github:

> wget https://github.com/JanDeDobbeleer/oh-my-posh/releases/latest/download/posh-linux-amd64 -O /usr/local/bin/oh-my-posh

and make it executable:

> chmod +x /usr/local/bin/oh-my-posh

Setup

Zsh Config

Create a .zshrc file in your homediretory and add or append the following lines in order to clone my settings. Again fell free to change everything.

# Enable colors for available commands
alias ls='ls --color=auto'
alias grep='grep --color=auto'
alias fgrep='fgrep --color=auto'
alias egrep='egrep --color=auto'
alias diff='diff --color=auto'
alias ip='ip --color=auto'

# Oh-my-posh Setup
eval "$(oh-my-posh init zsh --config "path to oh-my-posh theme")"

# Import Zsh Syntax Highlighting
source ~/.zsh/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh

# Adjusted Zsh syntax highlighting colors
ZSH_HIGHLIGHT_STYLES[unknown-token]=fg=007
ZSH_HIGHLIGHT_STYLES[single-quoted-argument]=fg=006
ZSH_HIGHLIGHT_STYLES[double-quoted-argument]=fg=006
ZSH_HIGHLIGHT_STYLES[single-hyphen-option]=fg=008
ZSH_HIGHLIGHT_STYLES[double-hyphen-option]=fg=008
ZSH_HIGHLIGHT_STYLES[comment]=fg=008
ZSH_HIGHLIGHT_STYLES[function]=fg=006
ZSH_HIGHLIGHT_STYLES[reserved-word]=fg=005
ZSH_HIGHLIGHT_STYLES[commandseparator]=fg=005
ZSH_HIGHLIGHT_STYLES[redirection]=fg=005

Set Zsh as the default shell

Use the following command to set Zsh as the default shell:

sudo chsh -s $(which zsh)

VSCode Integration

These are the json snippets I added to my VSCode settings, so that the integrated VSCode Terminal matches with the Windows Terminal:

// Set font
{
	"terminal.integrated.fontFamily": "MesloLGM NF",
	"terminal.integrated.fontSize": 14
}
// Add Color Scheme
{
	"workbench.colorCustomizations": {
		"terminal.foreground": "#F2F2F2",
		"terminal.ansiBlack": "#282C34",
		"terminal.ansiBlue": "#0078FF",
		"terminal.ansiCyan": "#4FB2FF",
		"terminal.ansiGreen": "#39FA73",
		"terminal.ansiMagenta": "#A140FC",
		"terminal.ansiRed": "#ED3E4E",
		"terminal.ansiWhite": "#F2F2F2",
		"terminal.ansiYellow": "#F1F139",
		"terminal.ansiBrightBlack": "#5A6374",
		"terminal.ansiBrightBlue": "#0078FF",
		"terminal.ansiBrightCyan": "#4FB2FF",
		"terminal.ansiBrightGreen": "#39FA73",
		"terminal.ansiBrightMagenta": "#A140FC",
		"terminal.ansiBrightRed": "#ED3E4E",
		"terminal.ansiBrightWhite": "#F2F2F2",
		"terminal.ansiBrightYellow": "#F1F139",
		"terminal.selectionBackground": "#FFFFFF",
		"terminalCursor.foreground": "#F2F2F2"
	}
}

IntelliJ Integration

Got to Settings > Editor > Color Scheme > Console Font to tweak the Console Font. My settings look like this:

IntelliJ Console font settings

Now go to Settings > Editor > Color Scheme > Console Colors and change the colors, so that they match with your color scheme.

Ready

That’s it. You should now have a decent looking Windows Terminal that matches with the integrated VSCode and IntelliJ terminal 😃

Featured image of post Colorful terminals with Oh My Posh and Windows Terminal

Linux

Configuring customizable and intuitive terminals with Oh My Posh

Introduction Link to this section

Oh My Posh is a tool that not only enhance the appearance of your shell, but also offers useful integrations that makes the use more intuitive and helps us be more productive.

I use it in WSL and in my home server and customized it to easily identify what shell I’m in:

My shells

Quick definition Link to this section

Just a quick definition of the terms Shell and Terminal:

  • Shell: the software that receives the input, process and returns and output (Examples: zsh, bash, PowerShell, cmd);
  • Terminal: the software that takes the input and passes on to the shell and then prints the shell output (Windows Terminal, VS Code Terminal, cmder).

Installing Oh My Posh Link to this section

To install Oh My Posh, we need to download the install script and run it:

curl -s https://ohmyposh.dev/install.sh | bash -s

And include its configuration in the run commands file of the shell you use.

In my case, I use zsh, so I include the following line to my ~/.zshrc file:

eval "$(oh-my-posh init zsh)"

Then exit the shell and enter again to load the configuration.

ℹ️ Here there is a list of configurations for the supported shells, including PowerShell and Cmd.

Installing a Nerd Font Link to this section

To use everything Oh My Posh offers, its essential to install a custom font that includes icons.
Oh My Posh recommends one of the Nerd Fonts.

To install the fonts on Windows:

  1. Download the font you like (I use Caskaydia Cove) from their page;

  2. Extract it in a temporary directory;

  3. Select all .ttf files;

  4. Right click and click Install or Install for all users.

Configuring The Terminal Link to this section

Then, we need to configure the terminal to use the font

⚠️ The fonts are needed in the system where you use the terminal. If you access a server via SSH, you only need the fonts in the system where you access it from.

Windows Terminal Link to this section

  1. Enter the Settings;
  2. Select the profile to configure;
  3. Click in Appearance;
  4. Select the font in Font face
  5. Click Save.

Then we can see that the icons are shown correctly:

Windows Terminal

VS Code Link to this section

  1. Enter the Settings (File > Preferences > Settings);
  2. Search for terminal font;
  3. Type the font name in Terminal > Integrated > Font Family. For Caskaydia Cove it can be CaskaydiaCove Nerd Font Mono.

Then we can see that the icons are shown correctly:

Windows Terminal

Themes Link to this section

Oh My Posh is highly customizable and has many themes (List here).

To use a theme, just download its json and use it when starting Oh My Posh.

In the example below, the theme is in ~/.poshthemes/aliens.omp.json:

eval "$(oh-my-posh init zsh --config ~/.poshthemes/aliens.omp.json)"

Then exit the shell and enter again to load the configuration.

Customizing your theme Link to this section

Oh My Posh has many segments that can be used. Some that I find interesting are:

  • Git: Can show the status of the git repo, files changed, rebase/merge status and many more;
  • Status Code: Shows the status of the last command executed, if they succeeded or not;
  • Root: Show if the logged user is root.

We can also use the Command segment to run any command and print the output.

As well as some configurations, for example:

  • Console title: Customize what is shown in the terminal title bar. I use it with a fixed text in my home server to easily identify when I’m connected to it;
  • Transient Prompt: Replaces the template for the shell history with a simpler one;
  • Tooltip: Show information on the right when a specified command is type. For example, show the git branch when “git” is typed.

💡 Oh My Posh is written in Go, so we can use Go Templates to customize many of its features with conditions, access environment variables and format texts. You can see some examples in my theme below.

Here there is an Unicode cheat sheet for Nerd Fonts to use when customizing the theme.

My theme Link to this section

In my theme I use 4 segments:

  • Session: Shows an icon, the logged in user and the hostname;
  • Path: Shows the current directory (I use the Agnoster Short style, but there are others);
  • Status: Shows an colored icon for the status of the last shell command (Successful/Failed);
  • Git: Shows the git status for the repository if the directory is one.

ℹ️ I change the color and the icon of the session segment according to what shell I’m using (server icon for home server, Ubuntu icon for Ubuntu in WSL).

ℹ💡 I use the console_title_template property to a different value (Ubuntu and Server) in each machine so the terminal title changes and I connect/disconnect via SSH.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
{
  "$schema": "https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/schema.json",
  "version": 2,
  "final_space": true,
  "console_title_template": "Ubuntu",
  "blocks": [
    {
      "type": "prompt",
      "alignment": "left",
      "segments": [
        {
          "type": "session",
          "style": "diamond",
          "foreground": "#FFFFFF",
          "background": "#dd4a14",          
          "leading_diamond": "\ue0b6",
          "template": "\ue73a {{ .UserName }}@{{ .HostName }} "
        },
        {
          "type": "path",
          "style": "powerline",
          "powerline_symbol": "\ue0b0",
          "foreground": "#ffffff",
          "background": "#207a26",
          "template": " {{ .Path }} ",
          "properties": {
            "folder_icon": "\uf6d7",
            "folder_separator_icon": "<transparent> \ue0bd </>",
            "home_icon": "\uf7db",
            "style": "agnoster_short"
          }
        },
        {
          "type": "status",
          "style": "powerline",
          "powerline_symbol": "\ue0b0",
          "foreground": "#ffffff",
          "background": "#00897b",
          "background_templates": [
            "{{ if .Error }}#890017{{ end }}"
          ],
          "template": " {{ if .Error }}\uea87{{ else }}\uf05d{{ end }} ",
          "properties": {
            "always_enabled": true
          }
        },
        {
          "type": "git",
          "style": "powerline",
          "powerline_symbol": "\ue0b0",
          "foreground": "#193549",
          "background": "#95ffa4",
          "template": " {{ .HEAD }}{{if .BranchStatus }} {{ .BranchStatus }}{{ end }}{{ if .Working.Changed }} \uf044 {{ .Working.String }}{{ end }}{{ if and (.Staging.Changed) (.Working.Changed) }} |{{ end }}{{ if .Staging.Changed }} \uf046 {{ .Staging.String }}{{ end }} "
        }
      ]
    }
  ]
}

References Link to this section

  • https://ohmyposh.dev/docs/

  • https://github.com/JanDeDobbeleer/oh-my-posh/

  • https://www.nerdfonts.com/

  • https://www.nerdfonts.com/cheat-sheet

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как изменить разрешение экрана на компьютере windows 10 горячие клавиши
  • Windows media player corrupted
  • Asus p5kpl am se драйвера windows 10 для windows
  • Хороший антивирус для windows 10 бесплатно на русском языке
  • Как узнать когда была установлена windows xp