Drawing tables in terminal using ANSI box characters

Allen Bargi picture Allen Bargi · Dec 20, 2010 · Viewed 10.5k times · Source

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?

Answer

Allen Bargi picture Allen Bargi · Dec 21, 2010

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)