Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing tables in terminal using ANSI box characters

I'm trying to print a table that's more pleasant to the eye than the pure text representation of it. basically I want to convert something like this:

+-----+--------+
| age | weight |
+-----+--------+
| 10  | 100    |
| 80  | 500    |
+-----+--------+

to something like this:

┌─────┬────────┐
| age | weight |
├─────┼────────┤
│ 10  │   100  │
│ 80  │  500   │
└─────┴────────┘

here is the screenshot of what I see in terminal:

in terminal looks like this

Notice the gaps between the rows. My problem is that they are not connecting properly while other Unix tools that use ANSI printing look fine in terminal. For example, tree, if I run tree -A in my terminal `I get this:

tree in terminal

notice how vertical lines are connected together. it's funny because when I copy and paste the output of tree into my text editor and run my script I get something like this:

tree in my code

Obviously I'm missing something about printing ANSI chars in terminal and couldn't find anything about it by googling it. can anyone shed some light on this topic?

like image 788
Allen Bargi Avatar asked Dec 20 '10 21:12

Allen Bargi


2 Answers

I guess I should answer my own question. After a little research and the help of friend and boss ,Linus, I found that I need to force the terminal to go to graphical mode first, then print the special characters and then return back to text mode. the ascii code for switching to graphical mode is 14 and 15 will return back to text mode. so here is the code in ruby:

printf("%c\n", 14)
printf("%c ", 0x6A) # ┘
printf("%c ", 0x6B) # ┐
printf("%c ", 0x6C) # ┌
printf("%c ", 0x6D) # └
printf("%c ", 0x6E) # ┼ 
printf("%c ", 0x71) # ─
printf("%c ", 0x74) # ├
printf("%c ", 0x75) # ┤
printf("%c ", 0x76) # ┴
printf("%c ", 0x77) # ┬
printf("%c\n", 0x78) # │


a = sprintf("%c", 0x6C) + # ┌
sprintf("%c", 0x71) + # ─
sprintf("%c", 0x71) + # ─
sprintf("%c", 0x71) + # ─
sprintf("%c", 0x71) + # ─
sprintf("%c", 0x71) + # ─
sprintf("%c", 0x71) + # ─
sprintf("%c\n", 0x6B) +  # ┐
sprintf("%c", 0x78) + # │
#print("      ")
"      " + 
sprintf("%c\n", 0x78) + # │
sprintf("%c", 0x6D) + # └
sprintf("%c", 0x71) + # ─
sprintf("%c", 0x71) + # ─
sprintf("%c", 0x71) + # ─
sprintf("%c", 0x71) + # ─
sprintf("%c", 0x71) + # ─
sprintf("%c", 0x71) + # ─
sprintf("%c", 0x6A)  # ┘

puts a

printf("%c\n", 15)
like image 106
Allen Bargi Avatar answered Oct 14 '22 12:10

Allen Bargi


You really should investigate ncurses and its variants. There are a range of different language bindings, though it was originally written for C. It provides a fairly substantial suite of libraries for producing TUIs (Text UIs) with windows, menus, boxed borders etc. Hit up wikipedia to start with to find some other references.

like image 37
Peter G. McDonald Avatar answered Oct 14 '22 12:10

Peter G. McDonald