I know tabs command can be used to set the tab width of the terminal, but how can I know current tab width of the terminal (assuming the tabs are equidistant)? I can't find related information in tabs manual, do I miss something?
Asked
Active
Viewed 1,308 times
6
-
That assumption is not always the case, note. – JdeBP Apr 27 '20 at 09:49
-
Tabs may not be equidistant. Do you want the positions for each tab? – Kusalananda May 31 '22 at 10:58
2 Answers
2
One could use a tab-width.sh script like that:
#!/usr/bin/env bash
echo -ne 'a\tb' &&
echo -ne "\033[6n" # ask the terminal for the position
read -rs -d\[ _ # discard the first part of the response
read -rs -dR foo # store the position in bash variable 'foo'
foo=$(cut -d";" -f2 <<< "$foo") # discard row number
printf "\r\e[0K%d\n" $((foo - 2)) # subtract 2 for 'a' and 'b'
Adapted from this answer on StackOverflow. Example:
$ tabs 10
$ ./tab-width.sh
10
$ tabs 20
$ ./tab-width.sh
20
$ tabs 3
$ ./tab-width.sh
3
Use carefully, the script has not been tested thoroughly. It seems to work well in most cases although the same value is returned for both 1 and 2:
$ tabs 1
$ ./tab-width.sh
2
$ tabs 2
$ ./tab-width.sh
2
but one should notice that output returned by echo -e 'a\tb' is also the same in both cases.
Arkadiusz Drabczyk
- 25,049
- 5
- 53
- 68
-
1Of course, on a real (late model) DEC VT one has the DECRQPSR request and the DECTABSR response. There are several emulators that implement this, including Christian Parpart's contour and MinTTY. – JdeBP Apr 27 '20 at 09:55
-
wow, that's some black magic. but it does not behave as one would expect in a script. – Ярослав Рахматуллин Mar 12 '22 at 16:23
-
0
Edit: The following doesn't actually work as I thought it did. Thank you @4wk_ for point this out in the comments :)
I've been using
echo $'\t' | wc -L
# typical output:
8
for this purpose.
echo $'\t'= prints a single tab characterwc= the "word counter" program-L= aka--max-line-length; the switch that tellswcto calculate the line length, with tabs properly expanded
I've found this method to be quite portable between different TTYs and shells. The only thing I would add to increase portability is simply change the echo to:
echo -e "\t"
but tomato-tomato really.
Pyr3z
- 1
- 1
-
2Does this expect tabs to be every eight characters? It's not always a valid assumption – roaima Apr 22 '22 at 20:21
-
-
1This was clever, but wrong: `wc` count what the OS see, not what is displayed to our terminals! So it always say "8", even if I change tabstop size with `tabs -4` (and confirm visually). – 4wk_ Jun 02 '22 at 15:32
-