psql
uses readline library (unless you specify -n
, --no-readline
option). Readline control sequences provide colorization capabilites.
For instance, I want to see the following prompt: %R%n@%/%x%#
. Description of percent-sequences you may find in the documentation. Here:
Sequence |
Meaning |
%n |
username |
@ |
as is |
%/ |
current database |
%R |
input state |
%x |
transaction status |
%# |
prompt character |
|
as is |
\set PROMPT1 '%R%n@%/%x%# '
\set PROMPT2 '%R%# '
psql
now prints commands like:
=myuser@mydb# select
-# 1;
Now we add colors. It is good to start with escape-sequences from Bash:
'%R\[\e[0;32m\]%n\[\e[0m\]@\[\e[0;33m\]%/\[\e[0;31m\]%x\[\e[0m\]%# '
^^^^^^^^^^^^ ^^^^^^^^^ ^^^^^^^^^^^^ ^^^^^^^^^^^^ ^^^^^^^^^
green reset yellow red reset
Then replace sequences with their octal equivalent:
Bash |
PSQL |
\[ |
%001 |
\] |
%002 |
\e |
%033 |
Step by step:
'%R%001\e[0;32m\]%n%001\e[0m\]@%001\e[0;33m\]%/%001\e[0;31m\]%x%001\e[0m\]%# '
\[ \[ \[ \[ \[
^^^^^^^^^^^^^^ ^^^^^^^^^^^ ^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^ ^^^^^^^^^^^
green reset yellow red reset
'%R%001\e[0;32m%002%n%001\e[0m%002@%001\e[0;33m%002%/%001\e[0;31m%002%x%001\e[0m%002%# '
\[ \] \[ \] \[ \] \[ \] \[ \]
^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^
green reset yellow red reset
'%R%001%033[0;32m%002%n%001%033[0m%002@%001%033[0;33m%002%/%001%033[0;31m%002%x%001%033[0m%002%# '
\[ \e \] \[ \e \] \[ \e \] \[ \e \] \[ \e \]
^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^
green reset yellow red reset
Now we have got color prompt:
\set PROMPT1 '%R%001%033[0;32m%002%n%001%033[0m%002@%001%033[0;33m%002%/%001%033[0;31m%002%x%001%033[0m%002%# '
\set PROMPT2 :PROMPT1
It is pretty easy to make mistake if you start colorization directly with %xxx
characters. Step by step process will help to avoid errors. In most cases unbalanced %001
and %002
characters can lead with incorrect visual representation of prompt when you scroll history: extra symbols appeared by you can't modify them and they don't affect you input.
At last, you may want to write your commands into ~/.psqlrc
.
$ cat ~/.psqlrc
\set PROMPT1 '%R%001%033[0;32m%002%n%001%033[0m%002@%001%033[0;33m%002%/%001%033[0;31m%002%x%001%033[0m%002%# '
\set PROMPT2 '%001%[%033[1;33;40m%]%002%R%001%[%033[0m%]%002%# '
readline
resolved to by default. Installingreadline
through Homebrew and manually compiling psql, passing the resulting paths asenv CFLAGS='-I ...' LDFLAGS='-L ...' ./configure
, gave me a psql that worked as expected, both for colors and navigation. – Journalize