Terminal control/Dimensions: Difference between revisions
m (→{{header|Phix}}: syntax coloured, marked p2js incompatible) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 4: | Line 4: | ||
=={{header|AArch64 Assembly}}== |
=={{header|AArch64 Assembly}}== |
||
{{works with|as|Raspberry Pi 3B version Buster 64 bits}} |
{{works with|as|Raspberry Pi 3B version Buster 64 bits}} |
||
<syntaxhighlight lang="aarch64 assembly"> |
|||
<lang AArch64 Assembly> |
|||
/* ARM assembly AARCH64 Raspberry PI 3B */ |
/* ARM assembly AARCH64 Raspberry PI 3B */ |
||
/* program terminalSize64.s */ |
/* program terminalSize64.s */ |
||
Line 98: | Line 98: | ||
/* for this file see task include a file in language AArch64 assembly */ |
/* for this file see task include a file in language AArch64 assembly */ |
||
.include "../includeARM64.inc" |
.include "../includeARM64.inc" |
||
</syntaxhighlight> |
|||
</lang> |
|||
<pre> |
<pre> |
||
Program start |
Program start |
||
Line 105: | Line 105: | ||
</pre> |
</pre> |
||
=={{header|Action!}}== |
=={{header|Action!}}== |
||
< |
<syntaxhighlight lang="action!">PROC Main() |
||
BYTE ROWCRS=$0054 ;Current cursor row |
BYTE ROWCRS=$0054 ;Current cursor row |
||
CARD COLCRS=$0055 ;Current cursor column |
CARD COLCRS=$0055 ;Current cursor column |
||
Line 120: | Line 120: | ||
PrintF("Number of colums: %U%E",width) |
PrintF("Number of colums: %U%E",width) |
||
PrintF("Number of rows: %B%E",height) |
PrintF("Number of rows: %B%E",height) |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Terminal_control_dimensions.png Screenshot from Atari 8-bit computer] |
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Terminal_control_dimensions.png Screenshot from Atari 8-bit computer] |
||
Line 129: | Line 129: | ||
=={{header|Applesoft BASIC}}== |
=={{header|Applesoft BASIC}}== |
||
< |
<syntaxhighlight lang="applesoftbasic">WIDTH = PEEK(33) |
||
HEIGHT = PEEK(35) - PEEK(34)</ |
HEIGHT = PEEK(35) - PEEK(34)</syntaxhighlight> |
||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang="rebol">print ["Terminal width:" terminal\width] |
||
print ["Terminal height:" terminal\height]</ |
print ["Terminal height:" terminal\height]</syntaxhighlight> |
||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
Line 141: | Line 141: | ||
{{trans|C}} |
{{trans|C}} |
||
AutoHotkey is not built for the console (it is GUI oriented) so we must call the WinAPI directly. |
AutoHotkey is not built for the console (it is GUI oriented) so we must call the WinAPI directly. |
||
< |
<syntaxhighlight lang="ahk">DllCall( "AllocConsole" ) ; create a console if not launched from one |
||
hConsole := DllCall( "GetStdHandle", int, STDOUT := -11 ) |
hConsole := DllCall( "GetStdHandle", int, STDOUT := -11 ) |
||
Line 155: | Line 155: | ||
columns := right - left + 1 |
columns := right - left + 1 |
||
rows := bottom - top + 1 |
rows := bottom - top + 1 |
||
MsgBox %columns% columns and %rows% rows</ |
MsgBox %columns% columns and %rows% rows</syntaxhighlight> |
||
=={{header|Axe}}== |
=={{header|Axe}}== |
||
Line 163: | Line 163: | ||
BaCon supports functions to retrieve the current number of <code>ROWS</code> and <code>COLUMNS</code>. |
BaCon supports functions to retrieve the current number of <code>ROWS</code> and <code>COLUMNS</code>. |
||
< |
<syntaxhighlight lang="freebasic">' ANSI terminal dimensions |
||
X = COLUMNS |
X = COLUMNS |
||
Y = ROWS |
Y = ROWS |
||
PRINT "X,Y: ", X, ",", Y</ |
PRINT "X,Y: ", X, ",", Y</syntaxhighlight> |
||
=={{header|Batch File}}== |
=={{header|Batch File}}== |
||
'''Screen Buffer Size:''' |
'''Screen Buffer Size:''' |
||
< |
<syntaxhighlight lang="dos">@echo off |
||
for /f "tokens=1,2 delims= " %%A in ('mode con') do ( |
for /f "tokens=1,2 delims= " %%A in ('mode con') do ( |
||
Line 180: | Line 180: | ||
echo Lines: %line% |
echo Lines: %line% |
||
echo Columns: %cols% |
echo Columns: %cols% |
||
exit /b 0</ |
exit /b 0</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>>Size.Bat |
<pre>>Size.Bat |
||
Line 190: | Line 190: | ||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
{{works with|BBC BASIC for Windows}} |
{{works with|BBC BASIC for Windows}} |
||
< |
<syntaxhighlight lang="bbcbasic"> dx% = @vdu.tr%-@vdu.tl% : REM Width of text viewport in pixels |
||
dy% = @vdu.tb%-@vdu.tt% : REM Height of text viewport in pixels</ |
dy% = @vdu.tb%-@vdu.tt% : REM Height of text viewport in pixels</syntaxhighlight> |
||
{{works with|all BBC BASIC}} |
{{works with|all BBC BASIC}} |
||
< |
<syntaxhighlight lang="bbcbasic"> PRINT:VDU 8:dx%=POS+1:PRINT : REM Width of text viewport in characters |
||
REPEAT:dy%=VPOS:PRINT:UNTIL VPOS=dy%:dy%=dy%+1 : REM Height of text viewport in characters</ |
REPEAT:dy%=VPOS:PRINT:UNTIL VPOS=dy%:dy%=dy%+1 : REM Height of text viewport in characters</syntaxhighlight> |
||
This has the side effect of scrolling the viewport up one line. |
This has the side effect of scrolling the viewport up one line. |
||
{{works with|BBC BASIC where VDU() is supported}} |
{{works with|BBC BASIC where VDU() is supported}} |
||
< |
<syntaxhighlight lang="bbcbasic"> dx% = VDU(10)-VDU(8)+1 : REM Width of text viewport in characters |
||
dy% = VDU(9)-VDU(11)+1 : REM Height of text viewport in characters</ |
dy% = VDU(9)-VDU(11)+1 : REM Height of text viewport in characters</syntaxhighlight> |
||
This has the side effect of scrolling the viewport up one line. |
This has the side effect of scrolling the viewport up one line. |
||
Line 210: | Line 210: | ||
{{works with|BSD|4.4}} |
{{works with|BSD|4.4}} |
||
< |
<syntaxhighlight lang="c">#include <sys/ioctl.h> /* ioctl, TIOCGWINSZ */ |
||
#include <err.h> /* err */ |
#include <err.h> /* err */ |
||
#include <fcntl.h> /* open */ |
#include <fcntl.h> /* open */ |
||
Line 236: | Line 236: | ||
close(fd); |
close(fd); |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
=== [[Windows]] === |
=== [[Windows]] === |
||
Line 242: | Line 242: | ||
{{works with|MinGW}} |
{{works with|MinGW}} |
||
< |
<syntaxhighlight lang="c">#include <windows.h> |
||
#include <wchar.h> |
#include <wchar.h> |
||
Line 269: | Line 269: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
Line 276: | Line 276: | ||
WindowHeight and WindowWidth are simply the size of the window, it only represents the active viewing area which may be larger or more commonly smaller than the size of the buffer. |
WindowHeight and WindowWidth are simply the size of the window, it only represents the active viewing area which may be larger or more commonly smaller than the size of the buffer. |
||
< |
<syntaxhighlight lang="csharp"> |
||
static void Main(string[] args) |
static void Main(string[] args) |
||
{ |
{ |
||
Line 294: | Line 294: | ||
Console.ReadLine(); |
Console.ReadLine(); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
On the author's system this results in the following output: |
On the author's system this results in the following output: |
||
Line 307: | Line 307: | ||
=={{header|COBOL}}== |
=={{header|COBOL}}== |
||
{{works with|OpenCOBOL}} |
{{works with|OpenCOBOL}} |
||
< |
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION. |
||
PROGRAM-ID. terminal-dimensions. |
PROGRAM-ID. terminal-dimensions. |
||
Line 333: | Line 333: | ||
GOBACK |
GOBACK |
||
.</ |
.</syntaxhighlight> |
||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
==={{header|ncurses}}=== |
==={{header|ncurses}}=== |
||
To interface the ncurses C library from Lisp, the ''croatoan'' library is used. |
To interface the ncurses C library from Lisp, the ''croatoan'' library is used. |
||
< |
<syntaxhighlight lang="lisp">(defun screen-dimensions () |
||
(with-screen (scr :input-blocking t :input-echoing nil :cursor-visible nil) |
(with-screen (scr :input-blocking t :input-echoing nil :cursor-visible nil) |
||
(let ((width (width scr)) |
(let ((width (width scr)) |
||
Line 345: | Line 345: | ||
(refresh scr) |
(refresh scr) |
||
;; wait for keypress |
;; wait for keypress |
||
(get-char scr))))</ |
(get-char scr))))</syntaxhighlight> |
||
=={{header|Euphoria}}== |
=={{header|Euphoria}}== |
||
< |
<syntaxhighlight lang="euphoria">include graphics.e |
||
sequence vc |
sequence vc |
||
Line 359: | Line 359: | ||
printf(1,"Terminal height is %d\n",term_height) |
printf(1,"Terminal height is %d\n",term_height) |
||
printf(1,"Terminal width is %d\n",term_width)</ |
printf(1,"Terminal width is %d\n",term_width)</syntaxhighlight> |
||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|F#}}== |
||
{{trans|C#}} |
{{trans|C#}} |
||
< |
<syntaxhighlight lang="fsharp">open System |
||
let bufferHeight = Console.BufferHeight |
let bufferHeight = Console.BufferHeight |
||
Line 378: | Line 378: | ||
Console.Write("Window Width: ") |
Console.Write("Window Width: ") |
||
Console.WriteLine(windowWidth) |
Console.WriteLine(windowWidth) |
||
Console.ReadLine()</ |
Console.ReadLine()</syntaxhighlight> |
||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
{{works with|GNU Forth}} {{works with|SwiftForth}} |
{{works with|GNU Forth}} {{works with|SwiftForth}} |
||
< |
<syntaxhighlight lang="forth">variable term-width |
||
variable term-height |
variable term-height |
||
Line 391: | Line 391: | ||
get-size ( width height ) swap |
get-size ( width height ) swap |
||
[then] |
[then] |
||
term-width ! term-height !</ |
term-width ! term-height !</syntaxhighlight> |
||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic">Dim As Integer w, h, p, bpp, tasa |
||
Dim driver_name As String |
Dim driver_name As String |
||
Screeninfo w, h, p, bpp, , tasa |
Screeninfo w, h, p, bpp, , tasa |
||
Line 416: | Line 416: | ||
Print " Tasa de refresco: "; tasa; " (Hz)" |
Print " Tasa de refresco: "; tasa; " (Hz)" |
||
Print " Nombre del driver: "; driver_name |
Print " Nombre del driver: "; driver_name |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
=={{header|Go}}== |
=={{header|Go}}== |
||
===Sub-repository=== |
===Sub-repository=== |
||
{{libheader|Go sub-repositories}} |
{{libheader|Go sub-repositories}} |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 437: | Line 437: | ||
} |
} |
||
fmt.Println(h, w) |
fmt.Println(h, w) |
||
}</ |
}</syntaxhighlight> |
||
===External command=== |
===External command=== |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 455: | Line 455: | ||
fmt.Sscan(string(d), &h, &w) |
fmt.Sscan(string(d), &h, &w) |
||
fmt.Println(h, w) |
fmt.Println(h, w) |
||
}</ |
}</syntaxhighlight> |
||
===Ncurses=== |
===Ncurses=== |
||
{{libheader|curses}} |
{{libheader|curses}} |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 475: | Line 475: | ||
height, width := s.MaxYX() |
height, width := s.MaxYX() |
||
fmt.Println(height, width) |
fmt.Println(height, width) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|J}}== |
=={{header|J}}== |
||
Line 483: | Line 483: | ||
Nevertheless, assuming J version 6 in its usual environment, to determine its width and height, in pixels, you can use: |
Nevertheless, assuming J version 6 in its usual environment, to determine its width and height, in pixels, you can use: |
||
<lang |
<syntaxhighlight lang="j">_2 {.qsmsize_jijs_''</syntaxhighlight> |
||
Note also that this will typically include 37 extra pixels horizontally and 79 extra pixels vertically, which are not available to display text. In other words, if the result was 700 500 you would really have 663 pixels of width and 421 pixels of height. |
Note also that this will typically include 37 extra pixels horizontally and 79 extra pixels vertically, which are not available to display text. In other words, if the result was 700 500 you would really have 663 pixels of width and 421 pixels of height. |
||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
< |
<syntaxhighlight lang="julia"> |
||
julia> using Gtk |
julia> using Gtk |
||
Line 495: | Line 495: | ||
julia> |
julia> |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
{{Works with|Ubuntu|14.04}} |
{{Works with|Ubuntu|14.04}} |
||
< |
<syntaxhighlight lang="scala">// version 1.1.2 |
||
/* |
/* |
||
Line 511: | Line 511: | ||
println("Lines = $lines") |
println("Lines = $lines") |
||
println("Columns = $columns") |
println("Columns = $columns") |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 523: | Line 523: | ||
Locomotive BASIC has no built-in command to get window dimensions, but there is a firmware call to &bb69 (TXT_GET_WINDOW) for this. So we have to use a snippet of Z80 machine code to call the firmware and copy the results from the DE and HL registers to RAM. It looks like this when disassembled: |
Locomotive BASIC has no built-in command to get window dimensions, but there is a firmware call to &bb69 (TXT_GET_WINDOW) for this. So we have to use a snippet of Z80 machine code to call the firmware and copy the results from the DE and HL registers to RAM. It looks like this when disassembled: |
||
< |
<syntaxhighlight lang="z80">4000 d5 push de |
||
4001 e5 push hl |
4001 e5 push hl |
||
4002 cd 69 bb call &bb69 |
4002 cd 69 bb call &bb69 |
||
Line 530: | Line 530: | ||
400c e1 pop hl |
400c e1 pop hl |
||
400d d1 pop de |
400d d1 pop de |
||
400e c9 ret</ |
400e c9 ret</syntaxhighlight> |
||
This routine gets POKEd into RAM (starting at address &4000) and CALLed from Locomotive BASIC, then the results are retrieved with PEEK: |
This routine gets POKEd into RAM (starting at address &4000) and CALLed from Locomotive BASIC, then the results are retrieved with PEEK: |
||
< |
<syntaxhighlight lang="locobasic">10 s=&4000:SYMBOL AFTER 256:MEMORY s-1 |
||
20 FOR i=0 to 14:READ a:POKE s+i,a:NEXT |
20 FOR i=0 to 14:READ a:POKE s+i,a:NEXT |
||
30 DATA &d5,&e5,&cd,&69,&bb,&ed,&53,&20,&40,&22,&22,&40,&e1,&d1,&c9 |
30 DATA &d5,&e5,&cd,&69,&bb,&ed,&53,&20,&40,&22,&22,&40,&e1,&d1,&c9 |
||
Line 540: | Line 540: | ||
50 h=PEEK(&4020)-PEEK(&4022)+1 |
50 h=PEEK(&4020)-PEEK(&4022)+1 |
||
60 w=PEEK(&4021)-PEEK(&4023)+1 |
60 w=PEEK(&4021)-PEEK(&4023)+1 |
||
70 PRINT "window width:"; w; ", height:"; h</ |
70 PRINT "window width:"; w; ", height:"; h</syntaxhighlight> |
||
In practice, one would prefer to write the machine code routine as a slightly more elaborate RSX ('''r'''esident '''s'''ystem e'''x'''tension) which is a freely relocatable and therefore more reusable Locomotive BASIC extension. The RSX routine might be called "getwh" and accept pointers to integers, which would simplify the BASIC code to: |
In practice, one would prefer to write the machine code routine as a slightly more elaborate RSX ('''r'''esident '''s'''ystem e'''x'''tension) which is a freely relocatable and therefore more reusable Locomotive BASIC extension. The RSX routine might be called "getwh" and accept pointers to integers, which would simplify the BASIC code to: |
||
< |
<syntaxhighlight lang="locobasic">10 w%=0:h%=0 ' initialize and force integer type |
||
20 |getwh,@w%,@h% ' call RSX and pass variables as pointers |
20 |getwh,@w%,@h% ' call RSX and pass variables as pointers |
||
30 PRINT "window width:"; w%; ", height:"; h%</ |
30 PRINT "window width:"; w%; ", height:"; h%</syntaxhighlight> |
||
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang="mathematica">WIDTH=RunThrough["tput cols", ""]; |
||
HEIGHT=RunThrough["tput lines", ""];</ |
HEIGHT=RunThrough["tput lines", ""];</syntaxhighlight> |
||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang="nim">import terminal |
||
let (width, height) = terminalSize() |
let (width, height) = terminalSize() |
||
echo "Terminal width: ", width |
echo "Terminal width: ", width |
||
echo "Terminal height: ", height</ |
echo "Terminal height: ", height</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 569: | Line 569: | ||
Using the library [http://forge.ocamlcore.org/projects/ansiterminal/ ANSITerminal] in the interactive loop: |
Using the library [http://forge.ocamlcore.org/projects/ansiterminal/ ANSITerminal] in the interactive loop: |
||
< |
<syntaxhighlight lang="ocaml">$ ocaml unix.cma -I +ANSITerminal ANSITerminal.cma |
||
# let width, height = ANSITerminal.size () ;; |
# let width, height = ANSITerminal.size () ;; |
||
val width : int = 126 |
val width : int = 126 |
||
val height : int = 47</ |
val height : int = 47</syntaxhighlight> |
||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">use Term::Size; |
||
($cols, $rows) = Term::Size::chars; |
($cols, $rows) = Term::Size::chars; |
||
print "The terminal has $cols columns and $rows lines\n";</ |
print "The terminal has $cols columns and $rows lines\n";</syntaxhighlight> |
||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
The buffer is usually somewhat larger (and never smaller) than the current physical screen size. I would guess that most applications are more interested in the latter. |
The buffer is usually somewhat larger (and never smaller) than the current physical screen size. I would guess that most applications are more interested in the latter. |
||
<!--< |
<!--<syntaxhighlight lang="phix">(notonline)--> |
||
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (video_config)</span> |
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (video_config)</span> |
||
<span style="color: #004080;">sequence</span> <span style="color: #000000;">vc</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">video_config</span><span style="color: #0000FF;">()</span> |
<span style="color: #004080;">sequence</span> <span style="color: #000000;">vc</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">video_config</span><span style="color: #0000FF;">()</span> |
||
Line 591: | Line 591: | ||
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Terminal screen height is %d\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">vc</span><span style="color: #0000FF;">[</span><span style="color: #004600;">VC_SCRNLINES</span><span style="color: #0000FF;">])</span> |
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Terminal screen height is %d\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">vc</span><span style="color: #0000FF;">[</span><span style="color: #004600;">VC_SCRNLINES</span><span style="color: #0000FF;">])</span> |
||
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Terminal screen width is %d\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">vc</span><span style="color: #0000FF;">[</span><span style="color: #000000;">VC_SCRNCOLS</span><span style="color: #0000FF;">])</span> |
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Terminal screen width is %d\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">vc</span><span style="color: #0000FF;">[</span><span style="color: #000000;">VC_SCRNCOLS</span><span style="color: #0000FF;">])</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 601: | Line 601: | ||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(setq |
||
Width (in '(tput cols) (read)) |
Width (in '(tput cols) (read)) |
||
Height (in '(tput lines) (read)) )</ |
Height (in '(tput lines) (read)) )</syntaxhighlight> |
||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
Line 609: | Line 609: | ||
This code is for Windows only. |
This code is for Windows only. |
||
< |
<syntaxhighlight lang="purebasic">Macro ConsoleHandle() |
||
GetStdHandle_( #STD_OUTPUT_HANDLE ) |
GetStdHandle_( #STD_OUTPUT_HANDLE ) |
||
EndMacro |
EndMacro |
||
Line 633: | Line 633: | ||
; |
; |
||
Print(#CRLF$+"Press ENTER to exit"):Input() |
Print(#CRLF$+"Press ENTER to exit"):Input() |
||
EndIf</ |
EndIf</syntaxhighlight> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
Line 641: | Line 641: | ||
This uses the [http://python.net/crew/theller/ctypes/ ctypes library] in order to get the console dimensions on Windows. This code is a slight refactoring of an [http://code.activestate.com/recipes/440694-determine-size-of-console-window-on-windows/ ActiveState Recipe]. For Linux, the tput utility is used. |
This uses the [http://python.net/crew/theller/ctypes/ ctypes library] in order to get the console dimensions on Windows. This code is a slight refactoring of an [http://code.activestate.com/recipes/440694-determine-size-of-console-window-on-windows/ ActiveState Recipe]. For Linux, the tput utility is used. |
||
< |
<syntaxhighlight lang="python">import os |
||
def get_windows_terminal(): |
def get_windows_terminal(): |
||
Line 667: | Line 667: | ||
print get_linux_terminal() if os.name == 'posix' else get_windows_terminal() |
print get_linux_terminal() if os.name == 'posix' else get_windows_terminal() |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
< |
<syntaxhighlight lang="racket"> |
||
#lang racket |
#lang racket |
||
(require (planet neil/charterm:3:0)) |
(require (planet neil/charterm:3:0)) |
||
(with-charterm |
(with-charterm |
||
(charterm-screen-size)) |
(charterm-screen-size)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
(formerly Perl 6) |
(formerly Perl 6) |
||
Using <i>stty</i> just for the heck of it. |
Using <i>stty</i> just for the heck of it. |
||
<lang |
<syntaxhighlight lang="raku" line>my $stty = qx[stty -a]; |
||
my $lines = $stty.match(/ 'rows ' <( \d+/); |
my $lines = $stty.match(/ 'rows ' <( \d+/); |
||
my $cols = $stty.match(/ 'columns ' <( \d+/); |
my $cols = $stty.match(/ 'columns ' <( \d+/); |
||
say "$lines $cols";</ |
say "$lines $cols";</syntaxhighlight> |
||
=={{header|Retro}}== |
=={{header|Retro}}== |
||
This information is provided by Retro in the '''ch''' (height) and '''cw''' (width) variables. You can manually obtain it using the io ports. |
This information is provided by Retro in the '''ch''' (height) and '''cw''' (width) variables. You can manually obtain it using the io ports. |
||
< |
<syntaxhighlight lang="retro">-3 5 out wait 5 in !cw |
||
-4 5 out wait 5 in !ch</ |
-4 5 out wait 5 in !ch</syntaxhighlight> |
||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
Line 698: | Line 698: | ||
Some REXX interpreters don't provide basic [[terminal control]] as part of the language. However, it's possible to determine the size of the terminal window by using external system commands: |
Some REXX interpreters don't provide basic [[terminal control]] as part of the language. However, it's possible to determine the size of the terminal window by using external system commands: |
||
< |
<syntaxhighlight lang="rexx">width = 'tput'( 'cols' ) |
||
height = 'tput'( 'lines' ) |
height = 'tput'( 'lines' ) |
||
say 'The terminal is' width 'characters wide' |
say 'The terminal is' width 'characters wide' |
||
say 'and has' height 'lines'</ |
say 'and has' height 'lines'</syntaxhighlight> |
||
===LINESIZE=== |
===LINESIZE=== |
||
The <code>LINESIZE</code> built-in function returns the (terminal) screen's width. It is supported by most (classic) REXX interpreters (and some others) such as: CMS REXX, TSO REXX, VSE REXX, the IBM REXX compiler, PC/REXX, Personal REXX, REXX/imc, R4 and ROO. A sample usage of it is: |
The <code>LINESIZE</code> built-in function returns the (terminal) screen's width. It is supported by most (classic) REXX interpreters (and some others) such as: CMS REXX, TSO REXX, VSE REXX, the IBM REXX compiler, PC/REXX, Personal REXX, REXX/imc, R4 and ROO. A sample usage of it is: |
||
< |
<syntaxhighlight lang="rexx">width=linesize()</syntaxhighlight> |
||
The above example makes use of '''LINESIZE''' REXX program (or BIF) which is used to determine the screen width (or linesize) of the terminal (console). |
The above example makes use of '''LINESIZE''' REXX program (or BIF) which is used to determine the screen width (or linesize) of the terminal (console). |
||
<br>The '''LINESIZE.REX''' REXX program is included here ──► [[LINESIZE.REX]]. |
<br>The '''LINESIZE.REX''' REXX program is included here ──► [[LINESIZE.REX]]. |
||
Line 712: | Line 712: | ||
===SCRSIZE=== |
===SCRSIZE=== |
||
<code>SCRSIZE</code> is another built-in function, and returns two integers: the screen depth and the screen width. A few classic REXX interpreters support it: PC/REXX, Personal REXX, R4 and ROO. |
<code>SCRSIZE</code> is another built-in function, and returns two integers: the screen depth and the screen width. A few classic REXX interpreters support it: PC/REXX, Personal REXX, R4 and ROO. |
||
< |
<syntaxhighlight lang="rexx"> parse value scrsize() with sd sw</syntaxhighlight> |
||
The above example makes use of '''SCRSIZE''' REXX program (of BIF) which is used to determine the screen size of the terminal (console). |
The above example makes use of '''SCRSIZE''' REXX program (of BIF) which is used to determine the screen size of the terminal (console). |
||
<br>The '''SCRSIZE.REX''' REXX program is included here ──► [[SCRSIZE.REX]].<br> |
<br>The '''SCRSIZE.REX''' REXX program is included here ──► [[SCRSIZE.REX]].<br> |
||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
system("mode 50,20") |
system("mode 50,20") |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby">def winsize |
||
# Ruby 1.9.3 added 'io/console' to the standard library. |
# Ruby 1.9.3 added 'io/console' to the standard library. |
||
require 'io/console' |
require 'io/console' |
||
Line 733: | Line 733: | ||
rows, cols = winsize |
rows, cols = winsize |
||
printf "%d rows by %d columns\n", rows, cols</ |
printf "%d rows by %d columns\n", rows, cols</syntaxhighlight> |
||
==={{libheader|curses}}=== |
==={{libheader|curses}}=== |
||
<code>Curses.lines</code> and <code>Curses.cols</code> return the size of the terminal. The program ''must'' call <code>Curses.init_screen</code>, because without this call, Curses might report 0 lines and 0 columns. Beware that <code>Curses.init_screen</code> also switches the terminal to screen-oriented mode, and fails on those terminals that cannot support curses. |
<code>Curses.lines</code> and <code>Curses.cols</code> return the size of the terminal. The program ''must'' call <code>Curses.init_screen</code>, because without this call, Curses might report 0 lines and 0 columns. Beware that <code>Curses.init_screen</code> also switches the terminal to screen-oriented mode, and fails on those terminals that cannot support curses. |
||
< |
<syntaxhighlight lang="ruby">require 'curses' |
||
begin |
begin |
||
Line 750: | Line 750: | ||
ensure |
ensure |
||
Curses.close_screen |
Curses.close_screen |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
{{Works with|Ubuntu|14.04}} |
{{Works with|Ubuntu|14.04}} |
||
< |
<syntaxhighlight lang="scala"> /* |
||
First execute the terminal command: 'export COLUMNS LINES' |
First execute the terminal command: 'export COLUMNS LINES' |
||
before running this program for it to work (returned 'null' sizes otherwise). |
before running this program for it to work (returned 'null' sizes otherwise). |
||
Line 760: | Line 760: | ||
val (lines, columns) = (System.getenv("LINES"), System.getenv("COLUMNS")) |
val (lines, columns) = (System.getenv("LINES"), System.getenv("COLUMNS")) |
||
println(s"Lines = $lines, Columns = $columns")</ |
println(s"Lines = $lines, Columns = $columns")</syntaxhighlight> |
||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
Line 768: | Line 768: | ||
''Height'' and ''width'' are based on terminfo respectively the Windows console API. |
''Height'' and ''width'' are based on terminfo respectively the Windows console API. |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
include "console.s7i"; |
include "console.s7i"; |
||
Line 782: | Line 782: | ||
# the program waits until Return/Enter is pressed. |
# the program waits until Return/Enter is pressed. |
||
readln; |
readln; |
||
end func;</ |
end func;</syntaxhighlight> |
||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
{{trans|Raku}} |
{{trans|Raku}} |
||
< |
<syntaxhighlight lang="ruby">var stty = `stty -a`; |
||
var lines = stty.match(/\brows\h+(\d+)/); |
var lines = stty.match(/\brows\h+(\d+)/); |
||
var cols = stty.match(/\bcolumns\h+(\d+)/); |
var cols = stty.match(/\bcolumns\h+(\d+)/); |
||
say "#{lines} #{cols}";</ |
say "#{lines} #{cols}";</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 797: | Line 797: | ||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
{{trans|UNIX Shell}} |
{{trans|UNIX Shell}} |
||
< |
<syntaxhighlight lang="tcl">set width [exec tput cols] |
||
set height [exec tput lines] |
set height [exec tput lines] |
||
puts "The terminal is $width characters wide and has $height lines"</ |
puts "The terminal is $width characters wide and has $height lines"</syntaxhighlight> |
||
=== Alternative === |
=== Alternative === |
||
'''Requires''': GNU coreutils |
'''Requires''': GNU coreutils |
||
< |
<syntaxhighlight lang="tcl">lassign [exec stty size] width height |
||
puts "The terminal is $width characters wide and has $height lines"</ |
puts "The terminal is $width characters wide and has $height lines"</syntaxhighlight> |
||
=={{header|UNIX Shell}}== |
=={{header|UNIX Shell}}== |
||
{{works with|Bourne Shell}} |
{{works with|Bourne Shell}} |
||
< |
<syntaxhighlight lang="bash">#!/bin/sh |
||
WIDTH=`tput cols` |
WIDTH=`tput cols` |
||
HEIGHT=`tput lines` |
HEIGHT=`tput lines` |
||
echo "The terminal is $WIDTH characters wide and has $HEIGHT lines."</ |
echo "The terminal is $WIDTH characters wide and has $HEIGHT lines."</syntaxhighlight> |
||
==={{libheader|termcap}}=== |
==={{libheader|termcap}}=== |
||
<div style="background-color: #ffc;">termcap is obsolete.</div> |
<div style="background-color: #ffc;">termcap is obsolete.</div> |
||
< |
<syntaxhighlight lang="bash">#!/bin/sh |
||
WIDTH=`tput co` |
WIDTH=`tput co` |
||
HEIGHT=`tput li` |
HEIGHT=`tput li` |
||
echo "The terminal is $WIDTH characters wide and has $HEIGHT lines."</ |
echo "The terminal is $WIDTH characters wide and has $HEIGHT lines."</syntaxhighlight> |
||
==={{header|C Shell}}=== |
==={{header|C Shell}}=== |
||
< |
<syntaxhighlight lang="csh">#!/bin/csh -f |
||
set WIDTH=`tput cols` |
set WIDTH=`tput cols` |
||
set HEIGHT=`tput lines` |
set HEIGHT=`tput lines` |
||
echo "The terminal is $WIDTH characters wide and has $HEIGHT lines."</ |
echo "The terminal is $WIDTH characters wide and has $HEIGHT lines."</syntaxhighlight> |
||
=={{header|Visual Basic}}== |
=={{header|Visual Basic}}== |
||
{{trans|C#}} |
{{trans|C#}} |
||
< |
<syntaxhighlight lang="vb">Module Module1 |
||
Sub Main() |
Sub Main() |
||
Line 846: | Line 846: | ||
End Sub |
End Sub |
||
End Module</ |
End Module</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
I put the built application in Desktop: |
I put the built application in Desktop: |
||
Line 867: | Line 867: | ||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
As there is currently no way to obtain this information via Wren CLI, we instead embed a Wren script in a C application and ask the host program to get it for us. |
As there is currently no way to obtain this information via Wren CLI, we instead embed a Wren script in a C application and ask the host program to get it for us. |
||
< |
<syntaxhighlight lang="ecmascript">/* terminal_control_dimensions.wren */ |
||
class C { |
class C { |
||
Line 878: | Line 878: | ||
System.print("The dimensions of the terminal are:") |
System.print("The dimensions of the terminal are:") |
||
System.print(" Width = %(w)") |
System.print(" Width = %(w)") |
||
System.print(" Height = %(h)")</ |
System.print(" Height = %(h)")</syntaxhighlight> |
||
<br> |
<br> |
||
We now embed this Wren script in the following C program, compile and run it. |
We now embed this Wren script in the following C program, compile and run it. |
||
< |
<syntaxhighlight lang="c">#include <stdlib.h> |
||
#include <stdio.h> |
#include <stdio.h> |
||
#include <string.h> |
#include <string.h> |
||
Line 972: | Line 972: | ||
free(script); |
free(script); |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 982: | Line 982: | ||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; |
||
int W, H; |
int W, H; |
||
[W:= Peek($40, $4A); \IBM-PC BIOS data |
[W:= Peek($40, $4A); \IBM-PC BIOS data |
||
Line 988: | Line 988: | ||
Text(0, "Terminal width and height = "); |
Text(0, "Terminal width and height = "); |
||
IntOut(0, W); ChOut(0, ^x); IntOut(0, H); |
IntOut(0, W); ChOut(0, ^x); IntOut(0, H); |
||
]</ |
]</syntaxhighlight> |
||
Output: |
Output: |
||
Line 996: | Line 996: | ||
=={{header|Yabasic}}== |
=={{header|Yabasic}}== |
||
< |
<syntaxhighlight lang="yabasic">clear screen |
||
w = peek("screenwidth") |
w = peek("screenwidth") |
||
h = peek("screenheight") |
h = peek("screenheight") |
||
Line 1,009: | Line 1,009: | ||
print " Ancho de la pantalla: ", w, " (pixel)" |
print " Ancho de la pantalla: ", w, " (pixel)" |
||
print "Altura de la pantalla: ", h, " (pixel)\n" |
print "Altura de la pantalla: ", h, " (pixel)\n" |
||
close window</ |
close window</syntaxhighlight> |
||
Line 1,015: | Line 1,015: | ||
Unix specific solution: |
Unix specific solution: |
||
{{trans|GO}} |
{{trans|GO}} |
||
< |
<syntaxhighlight lang="zkl">h,w:=System.popen("stty size","r").readln().split(); |
||
println(w," x ",h);</ |
println(w," x ",h);</syntaxhighlight> |
||
{{out}}<pre>91 x 24</pre> |
{{out}}<pre>91 x 24</pre> |
||
Revision as of 18:17, 28 August 2022
You are encouraged to solve this task according to the task description, using any language you may know.
Determine the height and width of the terminal, and store this information into variables for subsequent use.
AArch64 Assembly
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program terminalSize64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ TIOCGWINSZ, 0x5413
.equ IOCTL, 0x1D // Linux syscall
/*******************************************/
/* Structures */
/********************************************/
/* structure terminal size */
.struct 0
term_s_lines: // input modes
.struct term_s_lines + 2
term_s_cols: // output modes
.struct term_s_cols + 2
term_s_filler: // control modes
.struct term_s_filler + 12
term_fin:
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szMessStartPgm: .asciz "Program start \n"
szMessEndPgm: .asciz "Program normal end.\n"
szMessResult: .asciz "Terminal lines : @ cols : @ \n"
szMessErreur: .asciz "\033[31mError IOCTL.\n"
szCarriageReturn: .asciz "\n"
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
.align 4
sZoneConv: .skip 24
stTerminal: .skip term_fin // structure terminal
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main:
ldr x0,qAdrszMessStartPgm //display start message
bl affichageMess
/* read terminal dimensions */
mov x0,STDIN // input console
mov x1,TIOCGWINSZ // code IOCTL
ldr x2,qAdrstTerminal // structure address
mov x8,IOCTL // call system Linux
svc 0
cbnz x0,98f // error ?
ldr x2,qAdrstTerminal
ldrh w0,[x2,term_s_lines] // load two bytes
ldr x1,qAdrsZoneConv
bl conversion10 // and decimal conversion
ldr x0,qAdrszMessResult
bl strInsertAtChar // and insertion in message
mov x5,x0 // save address of new message
ldrh w0,[x2,term_s_cols] // load two bytes
ldr x1,qAdrsZoneConv
bl conversion10 // and decimal conversion
mov x0,x5 // restaur address of message
bl strInsertAtChar // and insertion in message
bl affichageMess
ldr x0,qAdrszMessEndPgm //display end message
bl affichageMess
b 100f
98: // error display
ldr x0,qAdrszMessErreur
bl affichageMess
mov x0,-1
100: //standard end of the program
mov x0,0 //return code
mov x8,EXIT //request to exit program
svc 0 //perform system call
qAdrszMessStartPgm: .quad szMessStartPgm
qAdrszMessEndPgm: .quad szMessEndPgm
qAdrszMessErreur: .quad szMessErreur
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrstTerminal: .quad stTerminal
qAdrszMessResult: .quad szMessResult
qAdrsZoneConv: .quad sZoneConv
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
Program start Terminal lines : 24 cols : 80 Program normal end.
Action!
PROC Main()
BYTE ROWCRS=$0054 ;Current cursor row
CARD COLCRS=$0055 ;Current cursor column
CARD width
BYTE height
Graphics(0)
Position(0,0) ;go to the top-left corner
Put(28) Put(30) ;go up and left - the bottom-right corner
width=COLCRS+1
height=ROWCRS+1
Position(2,1)
PrintF("Number of colums: %U%E",width)
PrintF("Number of rows: %B%E",height)
RETURN
- Output:
Screenshot from Atari 8-bit computer
Number of colums: 40 Number of rows: 24
Applesoft BASIC
WIDTH = PEEK(33)
HEIGHT = PEEK(35) - PEEK(34)
Arturo
print ["Terminal width:" terminal\width]
print ["Terminal height:" terminal\height]
AutoHotkey
AutoHotkey is not built for the console (it is GUI oriented) so we must call the WinAPI directly.
DllCall( "AllocConsole" ) ; create a console if not launched from one
hConsole := DllCall( "GetStdHandle", int, STDOUT := -11 )
MsgBox Resize the console...
VarSetCapacity(csbi, 22) ; CONSOLE_SCREEN_BUFFER_INFO structure
DllCall("GetConsoleScreenBufferInfo", UPtr, hConsole, UPtr, &csbi)
Left := NumGet(csbi, 10, "short")
Top := NumGet(csbi, 12, "short")
Right := NumGet(csbi, 14, "short")
Bottom := NumGet(csbi, 16, "short")
columns := right - left + 1
rows := bottom - top + 1
MsgBox %columns% columns and %rows% rows
Axe
Since Axe currently only supports the TI-83/84, the home screen dimensions are fixed at 16 columns by 8 rows.
BaCon
BaCon supports functions to retrieve the current number of ROWS
and COLUMNS
.
' ANSI terminal dimensions
X = COLUMNS
Y = ROWS
PRINT "X,Y: ", X, ",", Y
Batch File
Screen Buffer Size:
@echo off
for /f "tokens=1,2 delims= " %%A in ('mode con') do (
if "%%A"=="Lines:" set line=%%B
if "%%A"=="Columns:" set cols=%%B
)
echo Lines: %line%
echo Columns: %cols%
exit /b 0
- Output:
>Size.Bat Lines: 300 Columns: 80 >
BBC BASIC
dx% = @vdu.tr%-@vdu.tl% : REM Width of text viewport in pixels
dy% = @vdu.tb%-@vdu.tt% : REM Height of text viewport in pixels
PRINT:VDU 8:dx%=POS+1:PRINT : REM Width of text viewport in characters
REPEAT:dy%=VPOS:PRINT:UNTIL VPOS=dy%:dy%=dy%+1 : REM Height of text viewport in characters
This has the side effect of scrolling the viewport up one line.
dx% = VDU(10)-VDU(8)+1 : REM Width of text viewport in characters
dy% = VDU(9)-VDU(11)+1 : REM Height of text viewport in characters
This has the side effect of scrolling the viewport up one line.
C
C provides no standard way to find the size of a terminal.
BSD systems (and some other Unix clones) have TIOCGWINSZ. This ioctl(2) call gets the "window size" of a tty(4) device.
Almost all terminal devices can do NAWS (Negotiate About Window Size). A terminal emulator like xterm(1) should set the size. A network server like sshd(1) should copy the size from its client. Other devices, such as plain serial ports, might not know the window size.
#include <sys/ioctl.h> /* ioctl, TIOCGWINSZ */
#include <err.h> /* err */
#include <fcntl.h> /* open */
#include <stdio.h> /* printf */
#include <unistd.h> /* close */
int
main()
{
struct winsize ws;
int fd;
/* Open the controlling terminal. */
fd = open("/dev/tty", O_RDWR);
if (fd < 0)
err(1, "/dev/tty");
/* Get window size of terminal. */
if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
err(1, "/dev/tty");
printf("%d rows by %d columns\n", ws.ws_row, ws.ws_col);
printf("(%d by %d pixels)\n", ws.ws_xpixel, ws.ws_ypixel);
close(fd);
return 0;
}
Windows
Grab a console screen handle, then call GetConsoleScreenBufferInfo()
to get the information. Most consoles have a scroll bar and hold hundreds of lines, but the window shows only 25 or 50 lines. Use the window coordinates to calculate the window size.
#include <windows.h>
#include <wchar.h>
int
main()
{
HANDLE console;
CONSOLE_SCREEN_BUFFER_INFO info;
short rows;
short columns;
/* Create a handle to the console screen. */
console = CreateFileW(L"CONOUT$", GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
0, NULL);
if (console == INVALID_HANDLE_VALUE)
return 1;
/* Calculate the size of the console window. */
if (GetConsoleScreenBufferInfo(console, &info) == 0)
return 1;
CloseHandle(console);
columns = info.srWindow.Right - info.srWindow.Left + 1;
rows = info.srWindow.Bottom - info.srWindow.Top + 1;
wprintf(L"%d columns by %d rows\n", columns, rows);
return 0;
}
C#
The C# console has several properties to take note of. BufferHeight and BufferWidth are the valid writing area, the cursor can print anywhere within these bounds. This can be considered the actual terminal. WindowHeight and WindowWidth are simply the size of the window, it only represents the active viewing area which may be larger or more commonly smaller than the size of the buffer.
static void Main(string[] args)
{
int bufferHeight = Console.BufferHeight;
int bufferWidth = Console.BufferWidth;
int windowHeight = Console.WindowHeight;
int windowWidth = Console.WindowWidth;
Console.Write("Buffer Height: ");
Console.WriteLine(bufferHeight);
Console.Write("Buffer Width: ");
Console.WriteLine(bufferWidth);
Console.Write("Window Height: ");
Console.WriteLine(windowHeight);
Console.Write("Window Width: ");
Console.WriteLine(windowWidth);
Console.ReadLine();
}
On the author's system this results in the following output:
Buffer Height: 300 Buffer Width: 80 Window Height: 25 Window Width: 80
This perfectly demonstrates that the buffer may not be the same size as the window.
COBOL
IDENTIFICATION DIVISION.
PROGRAM-ID. terminal-dimensions.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 num-lines PIC 9(3).
01 num-cols PIC 9(3).
SCREEN SECTION.
01 display-screen.
03 LINE 01 COL 01 PIC 9(3) FROM num-lines.
03 LINE 01 COL 05 VALUE "rows by " .
03 LINE 01 COL 13 PIC 9(3) FROM num-cols.
03 LINE 01 COL 16 VALUE " columns.".
PROCEDURE DIVISION.
ACCEPT num-lines FROM LINES
ACCEPT num-cols FROM COLUMNS
DISPLAY display-screen
* This pauses the program, as ncurses will immediately revert
* back to the console when the program ends.
CALL "C$SLEEP" USING BY CONTENT 3
GOBACK
.
Common Lisp
ncurses
To interface the ncurses C library from Lisp, the croatoan library is used.
(defun screen-dimensions ()
(with-screen (scr :input-blocking t :input-echoing nil :cursor-visible nil)
(let ((width (width scr))
(height (height scr)))
(format scr "The current terminal screen is ~A lines high, ~A columns wide.~%~%" height width)
(refresh scr)
;; wait for keypress
(get-char scr))))
Euphoria
include graphics.e
sequence vc
integer term_height, term_width
vc = video_config()
term_height = vc[VC_LINES]
term_width = vc[VC_COLUMNS]
printf(1,"Terminal height is %d\n",term_height)
printf(1,"Terminal width is %d\n",term_width)
F#
open System
let bufferHeight = Console.BufferHeight
let bufferWidth = Console.BufferWidth
let windowHeight = Console.WindowHeight
let windowWidth = Console.WindowWidth
Console.Write("Buffer Height: ")
Console.WriteLine(bufferHeight)
Console.Write("Buffer Width: ")
Console.WriteLine(bufferWidth)
Console.Write("Window Height: ")
Console.WriteLine(windowHeight)
Console.Write("Window Width: ")
Console.WriteLine(windowWidth)
Console.ReadLine()
Forth
variable term-width
variable term-height
s" gforth" environment? [if]
2drop form ( height width )
[else] \ SwiftForth
get-size ( width height ) swap
[then]
term-width ! term-height !
FreeBASIC
Dim As Integer w, h, p, bpp, tasa
Dim driver_name As String
Screeninfo w, h, p, bpp, , tasa
Print !"Informaci¢n sobre el escritorio (terminal):\n"
Print " Ancho de la terminal: "; w; " (pixel)"
Print "Altura de la terminal: "; h; " (pixel)"
Print " Profundidad de color: "; p; " (bits)"
Print " Tasa de refresco: "; tasa; " (Hz)"
' Sets screen mode 13 (640*480, 8bpp)
Screen 12
Screeninfo w, h, p, bpp, , tasa, driver_name
Print !"Informaci¢n sobre el modo gr fico:\n"
Print " Ancho de la pantalla: "; w; " (pixel)"
Print "Altura de la pantalla: "; h; " (pixel)"
Print " Profundidad de color: "; p; " (bits)"
Print " Bytes por pixel: "; bpp
Print " Tasa de refresco: "; tasa; " (Hz)"
Print " Nombre del driver: "; driver_name
Sleep
Go
Sub-repository
package main
import (
"fmt"
"os"
"golang.org/x/crypto/ssh/terminal"
)
func main() {
w, h, err := terminal.GetSize(int(os.Stdout.Fd()))
if err != nil {
fmt.Println(err)
return
}
fmt.Println(h, w)
}
External command
package main
import (
"fmt"
"os"
"os/exec"
)
func main() {
var h, w int
cmd := exec.Command("stty", "size")
cmd.Stdin = os.Stdin
d, _ := cmd.Output()
fmt.Sscan(string(d), &h, &w)
fmt.Println(h, w)
}
Ncurses
package main
import (
"fmt"
"log"
"code.google.com/p/goncurses"
)
func main() {
s, err := goncurses.Init()
if err != nil {
log.Fatal("init:", err)
}
defer goncurses.End()
height, width := s.MaxYX()
fmt.Println(height, width)
}
J
This is not well supported in J, but since the terminal window can be resized at any time and can have its font changed and so on, good design generally dictates that this kind of information be ignored.
Nevertheless, assuming J version 6 in its usual environment, to determine its width and height, in pixels, you can use:
_2 {.qsmsize_jijs_''
Note also that this will typically include 37 extra pixels horizontally and 79 extra pixels vertically, which are not available to display text. In other words, if the result was 700 500 you would really have 663 pixels of width and 421 pixels of height.
Julia
julia> using Gtk
julia> screen_size()
(3840, 1080)
julia>
Kotlin
// version 1.1.2
/*
I needed to execute the terminal command: 'export COLUMNS LINES'
before running this program for it to work (returned 'null' sizes otherwise).
*/
fun main(args: Array<String>) {
val lines = System.getenv("LINES")
val columns = System.getenv("COLUMNS")
println("Lines = $lines")
println("Columns = $columns")
}
- Output:
Lines = 24 Columns = 80
Locomotive Basic
Locomotive BASIC has no built-in command to get window dimensions, but there is a firmware call to &bb69 (TXT_GET_WINDOW) for this. So we have to use a snippet of Z80 machine code to call the firmware and copy the results from the DE and HL registers to RAM. It looks like this when disassembled:
4000 d5 push de
4001 e5 push hl
4002 cd 69 bb call &bb69
4005 ed 53 20 40 ld (&4020),de
4009 22 22 40 ld (&4022),hl
400c e1 pop hl
400d d1 pop de
400e c9 ret
This routine gets POKEd into RAM (starting at address &4000) and CALLed from Locomotive BASIC, then the results are retrieved with PEEK:
10 s=&4000:SYMBOL AFTER 256:MEMORY s-1
20 FOR i=0 to 14:READ a:POKE s+i,a:NEXT
30 DATA &d5,&e5,&cd,&69,&bb,&ed,&53,&20,&40,&22,&22,&40,&e1,&d1,&c9
40 CALL s
50 h=PEEK(&4020)-PEEK(&4022)+1
60 w=PEEK(&4021)-PEEK(&4023)+1
70 PRINT "window width:"; w; ", height:"; h
In practice, one would prefer to write the machine code routine as a slightly more elaborate RSX (resident system extension) which is a freely relocatable and therefore more reusable Locomotive BASIC extension. The RSX routine might be called "getwh" and accept pointers to integers, which would simplify the BASIC code to:
10 w%=0:h%=0 ' initialize and force integer type
20 |getwh,@w%,@h% ' call RSX and pass variables as pointers
30 PRINT "window width:"; w%; ", height:"; h%
Mathematica/Wolfram Language
WIDTH=RunThrough["tput cols", ""];
HEIGHT=RunThrough["tput lines", ""];
Nim
import terminal
let (width, height) = terminalSize()
echo "Terminal width: ", width
echo "Terminal height: ", height
- Output:
Terminal width: 80 Terminal height: 24
OCaml
Using the library ANSITerminal in the interactive loop:
$ ocaml unix.cma -I +ANSITerminal ANSITerminal.cma
# let width, height = ANSITerminal.size () ;;
val width : int = 126
val height : int = 47
Perl
use Term::Size;
($cols, $rows) = Term::Size::chars;
print "The terminal has $cols columns and $rows lines\n";
Phix
The buffer is usually somewhat larger (and never smaller) than the current physical screen size. I would guess that most applications are more interested in the latter.
without js -- (video_config) sequence vc = video_config() printf(1,"Terminal buffer height is %d\n",vc[VC_LINES]) printf(1,"Terminal buffer width is %d\n",vc[VC_COLUMNS]) printf(1,"Terminal screen height is %d\n",vc[VC_SCRNLINES]) printf(1,"Terminal screen width is %d\n",vc[VC_SCRNCOLS])
- Output:
Terminal buffer height is 196 Terminal buffer width is 132 Terminal screen height is 25 Terminal screen width is 80
PicoLisp
(setq
Width (in '(tput cols) (read))
Height (in '(tput lines) (read)) )
PureBasic
PureBasic does not have native functions for reading the size of this window, but supports API-functions that allows this.
This code is for Windows only.
Macro ConsoleHandle()
GetStdHandle_( #STD_OUTPUT_HANDLE )
EndMacro
Procedure ConsoleWidth()
Protected CBI.CONSOLE_SCREEN_BUFFER_INFO
Protected hConsole = ConsoleHandle()
GetConsoleScreenBufferInfo_( hConsole, @CBI )
ProcedureReturn CBI\srWindow\right - CBI\srWindow\left + 1
EndProcedure
Procedure ConsoleHeight()
Protected CBI.CONSOLE_SCREEN_BUFFER_INFO
Protected hConsole = ConsoleHandle()
GetConsoleScreenBufferInfo_( hConsole, @CBI )
ProcedureReturn CBI\srWindow\bottom - CBI\srWindow\top + 1
EndProcedure
If OpenConsole()
x$=Str(ConsoleWidth())
y$=Str(ConsoleHeight())
PrintN("This window is "+x$+"x"+y$+ " chars.")
;
Print(#CRLF$+"Press ENTER to exit"):Input()
EndIf
Python
This uses the ctypes library in order to get the console dimensions on Windows. This code is a slight refactoring of an ActiveState Recipe. For Linux, the tput utility is used.
import os
def get_windows_terminal():
from ctypes import windll, create_string_buffer
h = windll.kernel32.GetStdHandle(-12)
csbi = create_string_buffer(22)
res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
#return default size if actual size can't be determined
if not res: return 80, 25
import struct
(bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy)\
= struct.unpack("hhhhHhhhhhh", csbi.raw)
width = right - left + 1
height = bottom - top + 1
return width, height
def get_linux_terminal():
width = os.popen('tput cols', 'r').readline()
height = os.popen('tput lines', 'r').readline()
return int(width), int(height)
print get_linux_terminal() if os.name == 'posix' else get_windows_terminal()
Racket
#lang racket
(require (planet neil/charterm:3:0))
(with-charterm
(charterm-screen-size))
Raku
(formerly Perl 6) Using stty just for the heck of it.
my $stty = qx[stty -a];
my $lines = $stty.match(/ 'rows ' <( \d+/);
my $cols = $stty.match(/ 'columns ' <( \d+/);
say "$lines $cols";
Retro
This information is provided by Retro in the ch (height) and cw (width) variables. You can manually obtain it using the io ports.
-3 5 out wait 5 in !cw
-4 5 out wait 5 in !ch
REXX
Using TPUT under Linux/Unix
Some REXX interpreters don't provide basic terminal control as part of the language. However, it's possible to determine the size of the terminal window by using external system commands:
width = 'tput'( 'cols' )
height = 'tput'( 'lines' )
say 'The terminal is' width 'characters wide'
say 'and has' height 'lines'
LINESIZE
The LINESIZE
built-in function returns the (terminal) screen's width. It is supported by most (classic) REXX interpreters (and some others) such as: CMS REXX, TSO REXX, VSE REXX, the IBM REXX compiler, PC/REXX, Personal REXX, REXX/imc, R4 and ROO. A sample usage of it is:
width=linesize()
The above example makes use of LINESIZE REXX program (or BIF) which is used to determine the screen width (or linesize) of the terminal (console).
The LINESIZE.REX REXX program is included here ──► LINESIZE.REX.
SCRSIZE
SCRSIZE
is another built-in function, and returns two integers: the screen depth and the screen width. A few classic REXX interpreters support it: PC/REXX, Personal REXX, R4 and ROO.
parse value scrsize() with sd sw
The above example makes use of SCRSIZE REXX program (of BIF) which is used to determine the screen size of the terminal (console).
The SCRSIZE.REX REXX program is included here ──► SCRSIZE.REX.
Ring
system("mode 50,20")
Ruby
def winsize
# Ruby 1.9.3 added 'io/console' to the standard library.
require 'io/console'
IO.console.winsize
rescue LoadError
# This works with older Ruby, but only with systems
# that have a tput(1) command, such as Unix clones.
[Integer(`tput li`), Integer(`tput co`)]
end
rows, cols = winsize
printf "%d rows by %d columns\n", rows, cols
Curses.lines
and Curses.cols
return the size of the terminal. The program must call Curses.init_screen
, because without this call, Curses might report 0 lines and 0 columns. Beware that Curses.init_screen
also switches the terminal to screen-oriented mode, and fails on those terminals that cannot support curses.
require 'curses'
begin
Curses.init_screen
r, c = Curses.lines, Curses.cols
Curses.setpos r / 2, 0
Curses.addstr "#{r} rows by #{c} columns".center(c)
Curses.getch
ensure
Curses.close_screen
end
Scala
/*
First execute the terminal command: 'export COLUMNS LINES'
before running this program for it to work (returned 'null' sizes otherwise).
*/
val (lines, columns) = (System.getenv("LINES"), System.getenv("COLUMNS"))
println(s"Lines = $lines, Columns = $columns")
Seed7
The functions height and width are portable and determine the dimensions of the console window. Height and width are based on terminfo respectively the Windows console API.
$ include "seed7_05.s7i";
include "console.s7i";
const proc: main is func
local
var text: console is STD_NULL;
begin
console := open(CONSOLE);
writeln(console, "height: " <& height(console) lpad 3);
writeln(console, "width: " <& width(console) lpad 3);
# Terminal windows often restore the previous
# content, when a program is terminated. Therefore
# the program waits until Return/Enter is pressed.
readln;
end func;
Sidef
var stty = `stty -a`;
var lines = stty.match(/\brows\h+(\d+)/);
var cols = stty.match(/\bcolumns\h+(\d+)/);
say "#{lines} #{cols}";
- Output:
24 80
Tcl
set width [exec tput cols]
set height [exec tput lines]
puts "The terminal is $width characters wide and has $height lines"
Alternative
Requires: GNU coreutils
lassign [exec stty size] width height
puts "The terminal is $width characters wide and has $height lines"
UNIX Shell
#!/bin/sh
WIDTH=`tput cols`
HEIGHT=`tput lines`
echo "The terminal is $WIDTH characters wide and has $HEIGHT lines."
#!/bin/sh
WIDTH=`tput co`
HEIGHT=`tput li`
echo "The terminal is $WIDTH characters wide and has $HEIGHT lines."
C Shell
#!/bin/csh -f
set WIDTH=`tput cols`
set HEIGHT=`tput lines`
echo "The terminal is $WIDTH characters wide and has $HEIGHT lines."
Visual Basic
Module Module1
Sub Main()
Dim bufferHeight = Console.BufferHeight
Dim bufferWidth = Console.BufferWidth
Dim windowHeight = Console.WindowHeight
Dim windowWidth = Console.WindowWidth
Console.Write("Buffer Height: ")
Console.WriteLine(bufferHeight)
Console.Write("Buffer Width: ")
Console.WriteLine(bufferWidth)
Console.Write("Window Height: ")
Console.WriteLine(windowHeight)
Console.Write("Window Width: ")
Console.WriteLine(windowWidth)
End Sub
End Module
- Output:
I put the built application in Desktop:
\Desktop>ConsoleApplication1 Buffer Height: 300 Buffer Width: 80 Window Height: 25 Window Width: 80 \Desktop>
After resizing the console:
\Desktop>ConsoleApplication1 Buffer Height: 300 Buffer Width: 80 Window Height: 14 Window Width: 49 \Desktop>
Wren
As there is currently no way to obtain this information via Wren CLI, we instead embed a Wren script in a C application and ask the host program to get it for us.
/* terminal_control_dimensions.wren */
class C {
foreign static terminalWidth
foreign static terminalHeight
}
var w = C.terminalWidth
var h = C.terminalHeight
System.print("The dimensions of the terminal are:")
System.print(" Width = %(w)")
System.print(" Height = %(h)")
We now embed this Wren script in the following C program, compile and run it.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include "wren.h"
void C_terminalWidth(WrenVM* vm) {
struct winsize w;
ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
wrenSetSlotDouble(vm, 0, (double)w.ws_col);
}
void C_terminalHeight(WrenVM* vm) {
struct winsize w;
ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
wrenSetSlotDouble(vm, 0, (double)w.ws_row);
}
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "C") == 0) {
if (isStatic && strcmp(signature, "terminalWidth") == 0) {
return C_terminalWidth;
} else if (isStatic && strcmp(signature, "terminalHeight") == 0) {
return C_terminalHeight;
}
}
}
return NULL;
}
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {
switch (errorType) {
case WREN_ERROR_COMPILE:
printf("[%s line %d] [Error] %s\n", module, line, msg);
break;
case WREN_ERROR_STACK_TRACE:
printf("[%s line %d] in %s\n", module, line, msg);
break;
case WREN_ERROR_RUNTIME:
printf("[Runtime Error] %s\n", msg);
break;
}
}
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
int main() {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.errorFn = &errorFn;
config.bindForeignMethodFn = &bindForeignMethod;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "terminal_control_dimensions.wren";
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
switch (result) {
case WREN_RESULT_COMPILE_ERROR:
printf("Compile Error!\n");
break;
case WREN_RESULT_RUNTIME_ERROR:
printf("Runtime Error!\n");
break;
case WREN_RESULT_SUCCESS:
break;
}
wrenFreeVM(vm);
free(script);
return 0;
}
- Output:
The dimensions of the terminal are: Width = 80 Height = 24
XPL0
include c:\cxpl\codes;
int W, H;
[W:= Peek($40, $4A); \IBM-PC BIOS data
H:= Peek($40, $84) + 1;
Text(0, "Terminal width and height = ");
IntOut(0, W); ChOut(0, ^x); IntOut(0, H);
]
Output:
80x25
Yabasic
clear screen
w = peek("screenwidth")
h = peek("screenheight")
print "Informaci¢n sobre el escritorio (terminal):"
print " Ancho de la terminal: ", w, " (pixel)"
print "Altura de la terminal: ", h, " (pixel)"
open window 640,480
w = peek("winheight")
h = peek("winwidth")
print "\n\nInformaci¢n sobre el modo gr fico:"
print " Ancho de la pantalla: ", w, " (pixel)"
print "Altura de la pantalla: ", h, " (pixel)\n"
close window
zkl
Unix specific solution:
h,w:=System.popen("stty size","r").readln().split();
println(w," x ",h);
- Output:
91 x 24
- Programming Tasks
- Terminal control
- Initialization
- AArch64 Assembly
- Action!
- Applesoft BASIC
- Arturo
- AutoHotkey
- Axe
- BaCon
- Batch File
- BBC BASIC
- C
- BSD libc
- C sharp
- COBOL
- Common Lisp
- Ncurses
- Euphoria
- F Sharp
- Forth
- FreeBASIC
- Go
- Go sub-repositories
- Curses
- J
- Julia
- Kotlin
- Locomotive Basic
- Mathematica
- Wolfram Language
- Nim
- OCaml
- Perl
- Phix
- PicoLisp
- PureBasic
- Python
- Ctypes
- Racket
- Raku
- Retro
- REXX
- Ring
- Ruby
- Scala
- Seed7
- Sidef
- Tcl
- UNIX Shell
- Termcap
- C Shell
- Visual Basic
- Wren
- XPL0
- Yabasic
- Zkl
- ACL2/Omit
- GUISS/Omit
- Maxima/Omit
- PARI/GP/Omit
- TI-83 BASIC/Omit