Terminal control/Clear the screen

From Rosetta Code
Task
Terminal control/Clear the screen
You are encouraged to solve this task according to the task description, using any language you may know.

Clear the terminal window.

6502 Assembly[edit]

Works with: [VICE]

This example has been written for the C64 and uses the CHROUT KERNAL routine. Compile with the Turbo Macro Pro cross assembler:

tmpx -i clrscr.s -o bin/clrscr.prg

Run with:

SYS680
; C64 - Terminal control: Clear the screen
 
; *** labels ***
 
chrout = $ffd2
 
; *** main ***
 
*=$02a8  ; sys 680
 
lda clr  ; A = {CLR}
jsr chrout  ; Output a character in A to the current
 ; output device (default: screen).
rts
 
; *** data ***
 
clr .byte $93  ; the CLR control code
 ; see https://en.wikipedia.org/wiki/PETSCII
 
Works with: [6502asm.com] version 1.2
Works with: [6502asm.com] version 1.5 beta

The 6502asm.com emulator has a 32x32 pixel screen. First we fill this screen with random colored pixels, wait for a keypress and then "clear" the screen (fill it with black pixels).

; 6502asm.com - Clear the screen
 
lda #$00  ; store the start address of the screen ($200)
sta $00  ; at $00 and $01 (high byte in $01)
lda #$02
sta $01
 
ldy #$00  ; Y = 0
fillscreen:
lda $fe  ; A = random number from $fe
sta ($00),y  ; put pixel (random color) to the screen
iny  ; Y++
bne fillscreen  ; loop if Y!=0
inc $01  ; increase address high byte
lda $01
cmp #$06  ; A==6? (screen ends at $05ff)
bne fillscreen  ; no -> loop
 
waitforkeypress:
lda $ff  ; $ff is 0 if no key has been pressed
beq waitforkeypress
 
ldx #$00
lda #$00  ; black
clearscreen:
sta $0200,x
sta $0300,x
sta $0400,x
sta $0500,x
inx
bne clearscreen
 

Ada[edit]

For systems with ANSI terminal handling:

with Ada.Text_IO;
procedure CLS is
begin
Ada.Text_IO.Put(ASCII.ESC & "[2J");
end CLS;

AutoHotkey[edit]

Reference: http://www.autohotkey.com/forum/topic76532.html

RunWait %comspec% /c cls

AWK[edit]

system("clear")

Axe[edit]

ClrHome

BASIC[edit]

Works with: QBasic
Works with: Locomotive Basic
Works with: ZX Spectrum Basic
Works with: BBC BASIC
CLS

Applesoft BASIC[edit]

HOME

BBC BASIC[edit]

      CLS

or

      VDU 12

or

      PRINT CHR$(12);

GW-BASIC[edit]

10 CLS

PureBasic[edit]

Clears the whole console content using the current background color.

ClearConsole()

Batch File[edit]

CLS

beeswax[edit]

Using the ANSI escape sequence Esc[2J.

_3F..}`[2J`

Befunge[edit]

Assuming a terminal with support for ANSI escape sequences.

"J2["39*,,,,@

Blast[edit]

clear

Bracmat[edit]

sys$cls&

C[edit]

The C version of the Minesweeper game uses curses.

If perhaps clear screen isn't used, call the function cls to do the trick.

void cls(void) {
printf("\33[2J");
}

Here is the cheaty way no one likes, only works on Windows.

#include <stdio.h>
#include <stdlib.h>
 
void main() {
printf ("clearing screen");
getchar();
system("cls");
}

C#[edit]

System.Console.Clear();

COBOL[edit]

       PROGRAM-ID. blank-terminal.
 
DATA DIVISION.
SCREEN SECTION.
01 blank-screen BLANK SCREEN.
 
PROCEDURE DIVISION.
DISPLAY blank-screen
 
GOBACK
.

Comal[edit]

PAGE

Common Lisp[edit]

 
(format t "~C[2J" #\Esc)
 

or it could be done passing the 'clear' command to the shell

 
(defun sh (cmd)
"A multi-implementation function equivalent for the C function system"
#+clisp (shell cmd)
#+ecl (si:system cmd)
#+sbcl (sb-ext:run-program "/bin/sh" (list "-c" cmd) :input nil :output *standard-output*)
#+clozure (ccl:run-program "/bin/sh" (list "-c" cmd) :input nil :output *standard-output*))
(sh "clear")
 

D[edit]

extern (C) nothrow {
void disp_open();
void disp_move(int, int);
void disp_eeop();
void disp_close();
}
 
void main() {
disp_open();
disp_move(0, 0);
disp_eeop();
disp_close();
}

Erlang[edit]

 
clear()->io:format(os:cmd("clear")).
 

Euphoria[edit]

clear_screen()

F#[edit]

open System
 
Console.Clear()

Forth[edit]

page

Fortran[edit]

Fortran 2008:

program clear
character(len=:), allocatable :: clear_command
clear_command = "clear" !"cls" on Windows, "clear" on Linux and alike
call execute_command_line(clear_command)
end program

Intel Fortran on Windows[edit]

Using console functions, one can also clear the screen without using a system command. See also Clearing the Screen on MSDN.

program clear
use kernel32
implicit none
integer(HANDLE) :: hStdout
hStdout = GetStdHandle(STD_OUTPUT_HANDLE)
call clear_console(hStdout)
contains
subroutine clear_console(hConsole)
integer(HANDLE) :: hConsole
type(T_COORD) :: coordScreen = T_COORD(0, 0)
integer(DWORD) :: cCharsWritten
type(T_CONSOLE_SCREEN_BUFFER_INFO) :: csbi
integer(DWORD) :: dwConSize
 
if (GetConsoleScreenBufferInfo(hConsole, csbi) == 0) return
dwConSize = csbi%dwSize%X * csbi%dwSize%Y
 
if (FillConsoleOutputCharacter(hConsole, SCHAR_" ", dwConSize, &
coordScreen, loc(cCharsWritten)) == 0) return
 
if (GetConsoleScreenBufferInfo(hConsole, csbi) == 0) return
 
if (FillConsoleOutputAttribute(hConsole, csbi%wAttributes, &
dwConSize, coordScreen, loc(cCharsWritten)) == 0) return
 
if (SetConsoleCursorPosition(hConsole, coordScreen) == 0) return
end subroutine
end program

GNU Fortran on Windows[edit]

The preceding program can be compiled with GNU Fortran, with the following interface module for Windows API.

module kernel32
use iso_c_binding
implicit none
integer, parameter :: HANDLE = C_INTPTR_T
integer, parameter :: PVOID = C_INTPTR_T
integer, parameter :: LPDWORD = C_INTPTR_T
integer, parameter :: BOOL = C_INT
integer, parameter :: SHORT = C_INT16_T
integer, parameter :: WORD = C_INT16_T
integer, parameter :: DWORD = C_INT32_T
integer, parameter :: SCHAR = C_CHAR
integer(DWORD), parameter :: STD_INPUT_HANDLE = -10
integer(DWORD), parameter :: STD_OUTPUT_HANDLE = -11
integer(DWORD), parameter :: STD_ERROR_HANDLE = -12
 
type, bind(C) :: T_COORD
integer(SHORT) :: X, Y
end type
 
type, bind(C) :: T_SMALL_RECT
integer(SHORT) :: Left
integer(SHORT) :: Top
integer(SHORT) :: Right
integer(SHORT) :: Bottom
end type
 
type, bind(C) :: T_CONSOLE_SCREEN_BUFFER_INFO
type(T_COORD) :: dwSize
type(T_COORD) :: dwCursorPosition
integer(WORD) :: wAttributes
type(T_SMALL_RECT) :: srWindow
type(T_COORD) :: dwMaximumWindowSize
end type
 
interface
function FillConsoleOutputCharacter(hConsoleOutput, cCharacter, &
nLength, dwWriteCoord, lpNumberOfCharsWritten) &
bind(C, name="FillConsoleOutputCharacterA")
import BOOL, C_CHAR, SCHAR, HANDLE, DWORD, T_COORD, LPDWORD
!GCC$ ATTRIBUTES STDCALL :: FillConsoleOutputCharacter
integer(BOOL) :: FillConsoleOutputCharacter
integer(HANDLE), value :: hConsoleOutput
character(kind=SCHAR), value :: cCharacter
integer(DWORD), value :: nLength
type(T_COORD), value :: dwWriteCoord
integer(LPDWORD), value :: lpNumberOfCharsWritten
end function
end interface
 
interface
function FillConsoleOutputAttribute(hConsoleOutput, wAttribute, &
nLength, dwWriteCoord, lpNumberOfAttrsWritten) &
bind(C, name="FillConsoleOutputAttribute")
import BOOL, HANDLE, WORD, DWORD, T_COORD, LPDWORD
!GCC$ ATTRIBUTES STDCALL :: FillConsoleOutputAttribute
integer(BOOL) :: FillConsoleOutputAttribute
integer(HANDLE), value :: hConsoleOutput
integer(WORD), value :: wAttribute
integer(DWORD), value :: nLength
type(T_COORD), value :: dwWriteCoord
integer(LPDWORD), value :: lpNumberOfAttrsWritten
end function
end interface
 
interface
function GetConsoleScreenBufferInfo(hConsoleOutput, &
lpConsoleScreenBufferInfo) &
bind(C, name="GetConsoleScreenBufferInfo")
import BOOL, HANDLE, T_CONSOLE_SCREEN_BUFFER_INFO
!GCC$ ATTRIBUTES STDCALL :: GetConsoleScreenBufferInfo
integer(BOOL) :: GetConsoleScreenBufferInfo
integer(HANDLE), value :: hConsoleOutput
type(T_CONSOLE_SCREEN_BUFFER_INFO) :: lpConsoleScreenBufferInfo
end function
end interface
 
interface
function SetConsoleCursorPosition(hConsoleOutput, dwCursorPosition) &
bind(C, name="SetConsoleCursorPosition")
import BOOL, HANDLE, T_COORD
!GCC$ ATTRIBUTES STDCALL :: SetConsoleCursorPosition
integer(BOOL) :: SetConsoleCursorPosition
integer(HANDLE), value :: hConsoleOutput
type(T_COORD), value :: dwCursorPosition
end function
end interface
 
interface
function GetStdHandle(nStdHandle) bind(C, name="GetStdHandle")
import HANDLE, DWORD
!GCC$ ATTRIBUTES STDCALL :: GetStdHandle
integer(HANDLE) :: GetStdHandle
integer(DWORD), value :: nStdHandle
end function
end interface
end module
 

FreeBASIC[edit]

' FB 1.05.0 Win64
 
' FreeBASIC has a built in Cls command which clears the console on Windows
' but it may still be possible to scroll the console to view its
' previous contents. The following command prevents this.
 
Shell("Cls")
Sleep

Go[edit]

External command[edit]

Probably most reliable way to clear the screen.

package main
 
import (
"os"
"os/exec"
)
 
func main() {
c := exec.Command("clear")
c.Stdout = os.Stdout
c.Run()
}

ANSI escape code[edit]

Simplest, if your terminal supports the ANSI code you want.

package main
 
import "fmt"
 
func main() {
fmt.Print("\033[2J")
}

Ncurses[edit]

More complex, but works across multiple terminal types.

Library: curses
package main
 
import (
"log"
"time"
 
"code.google.com/p/goncurses"
)
 
func main() {
s, err := goncurses.Init()
if err != nil {
log.Fatal("goncurses:", err)
}
defer goncurses.End()
s.Println("Clearing screen...")
s.Refresh()
time.Sleep(1 * time.Second)
 
s.Clear() // clear screen
 
// Goncurses saves the screen on Init and restores it on End. This
// GetChar() allows you to see the effect of the program before it exits.
s.GetChar() // press any key to continue
}

GUISS[edit]

This will only work if the terminal is sitting at a prompt.

Window:Terminal,Type:clear[enter]

Haskell[edit]

 
import System.Console.ANSI
 
main = clearScreen
 

Icon and Unicon[edit]

Example works for both Icon and Unicon. Determine which system command to call by querying &features at run time. Alternately, the related preprocessor symbols can be used to select the operating system.

procedure main ()
if &features == "MS Windows" then system("cls") # Windows
else if &features == "UNIX" then system("clear") # Unix
end

J[edit]

Note: this is specific the java+gdi based J ide.

smwrite_jijs_ ''

Java[edit]

Using the ANSI escape sequence:

public class Clear
{
public static void main (String[] args)
{
System.out.print("\033[2J");
}
}

An alternative sequence:

public class Clear
{
public static void main (String[] args)
{
System.out.print("\033\143");
}
}

jq[edit]

"\u001B[2J"

Example:

$ jq -n '"\u001B[2J"'

Kotlin[edit]

Works with: Ubuntu version 14.04
// version 1.1.1
 
fun main(args: Array<String>) {
println("\u001Bc") // Esc + c
}

Lasso[edit]

local(
esc = decode_base64('Gw==')
)
 
stdout(#esc + '[2J')

[edit]

cleartext

There is a separate command to reset the turtle graphics window.

clearscreen
cs  ; abbreviation for clearscreen
clean  ; like cs, but doesn't reset turtle position

Lua[edit]

os.execute( "clear" )

will not work because "clear" is not a command although you can use

os.execute( "cls" )

Mathematica[edit]

Delegating to clear on terminal enabled OS(Mac Os, Linux)

Run["clear"];

Nemerle[edit]

Exactly as C#. Because of possible (probable) ambiguity, this is one time it may be prudent to use:

Console.Clear();

rather than importing the Console class with using System.Console; and calling as:

Clear();

NewLISP[edit]

 
(! "clear")
 

In the newLISP command shell, this syntax is also proper:

 
!clear
 

Nim[edit]

import osproc
discard execCmd "clear"

OCaml[edit]

Using the library ANSITerminal:

#load "unix.cma"
#directory "+ANSITerminal"
#load "ANSITerminal.cma"
open ANSITerminal
 
let () =
erase Screen

Octave[edit]

 system clear;
 system('clear');

Pascal[edit]

clrscr;

Perl[edit]

Assuming some ANSI terminal, easiest way is call your system's clear command:

system('clear')

If it's needed often:

$clear = `clear`; # clear simply prints some escape sequence, cache it
#... later:
print $clear;

We can also obtain the sequence using the Term::Cap module:

use Term::Cap;
 
$terminal = Term::Cap->Tgetent();
$clear = $terminal->Tputs('cl');
print $clear;

Perl 6[edit]

sub clear { print state $ = qx[clear] }
clear;

Phix[edit]

clear_screen()

PicoLisp[edit]

(call 'clear)

PowerShell[edit]

Clear-Host

ProDOS[edit]

clearscurrentscreentext

Python[edit]

Works with: Python version 2.6
Works with: Ubuntu version 10.10

To clear the screen on Windows, replace 'clear' with 'cls'

import os
os.system("clear")

Or similar to C example (won't work in Winsows console, since it does not recognize ANSI sequences):

print "\33[2J"

On Windows, using functions from the kernel32 DLL:

from ctypes import *
 
STD_OUTPUT_HANDLE = -11
 
class COORD(Structure):
pass
 
COORD._fields_ = [("X", c_short), ("Y", c_short)]
 
class SMALL_RECT(Structure):
pass
 
SMALL_RECT._fields_ = [("Left", c_short), ("Top", c_short), ("Right", c_short), ("Bottom", c_short)]
 
class CONSOLE_SCREEN_BUFFER_INFO(Structure):
pass
 
CONSOLE_SCREEN_BUFFER_INFO._fields_ = [
("dwSize", COORD),
("dwCursorPosition", COORD),
("wAttributes", c_ushort),
("srWindow", SMALL_RECT),
("dwMaximumWindowSize", COORD)
]
 
def clear_console():
h = windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
 
csbi = CONSOLE_SCREEN_BUFFER_INFO()
windll.kernel32.GetConsoleScreenBufferInfo(h, pointer(csbi))
dwConSize = csbi.dwSize.X * csbi.dwSize.Y
 
scr = COORD(0, 0)
windll.kernel32.FillConsoleOutputCharacterA(h, c_char(b" "), dwConSize, scr, pointer(c_ulong()))
windll.kernel32.FillConsoleOutputAttribute(h, csbi.wAttributes, dwConSize, scr, pointer(c_ulong()))
windll.kernel32.SetConsoleCursorPosition(h, scr)
 
clear_console()

Racket[edit]

 
#lang racket
(require (planet neil/charterm:3:0))
(with-charterm
(void (charterm-clear-screen)))
 

Retro[edit]

clear

REXX[edit]

generic[edit]

The REXX programming language does not include a facility to clear the screen natively.

However, it is possile to execute an external system command to achieve this task.

Below is some generic-type boilerplate (REXX) code which (possibly) determines:

  • which REXX is being used
  • which operating system is being used
  • which (external) program to clear the screen


Also, not germane to this Rosetta Code task, the boilerplate code also possibly determines (among other things):

  • if a particular documentation is to be shown
  • which system pool name is to be used for system environmental variables
  • which version of REXX is being used
  • if the program is being invoked as a function, command, or subroutine


The following code works for:

  • PC/REXX
  • Personal REXX
  • CMS REXX
  • TSO REXX
  • R4 REXX
  • ROO REXX
  • KEXX
  • REXX compiler
  • Regina REXX


The intent of the program's boilerplate code is to be able to be executed under most REXXes under most operating systems without changing the boilerplate REXX code.

/*REXX boilerplate determines how to clear screen (under various REXXes)*/
trace off; parse arg ! /*turn off tracing; get C.L. args*/
if !all(arg()) then exit /*Doc request? Show, then exit.*/
if !cms then address '' /*Is this CMS? Use this address.*/
 
!cls /*clear the (terminal) screen. */ /* ◄═══ this is where "it" happens.*/
 
exit /*stick a fork in it, we're done.*/
/*═════════════════════════════general 1-line subs══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════*/
!all:  !!=!;!=space(!);upper !;call !fid;!nt=right(!var('OS'),2)=='NT';!cls=word('CLS VMFCLEAR CLRSCREEN',1+!cms+!tso*2);if arg(1)\==1 then return 0;if wordpos(!,'? ?SAMPLES ?AUTHOR ?FLOW')==0 then return 0;!call=']$H';call '$H' !fn !;!call=;return 1
!cal: if symbol('!CALL')\=="VAR" then !call=; return !call
!env:  !env='ENVIRONMENT'; if !sys=='MSDOS'|!brexx|!r4|!roo then !env='SYSTEM'; if !os2 then !env='OS2'!env; !ebcdic=1=='f0'x; if !crx then !env='DOS'; return
!fid: parse upper source !sys !fun !fid . 1 . . !fn !ft !fm .; call !sys; if !dos then do; _=lastpos('\',!fn); !fm=left(!fn,_); !fn=substr(!fn,_+1); parse var !fn !fn '.' !ft; end; return word(0 !fn !ft !fm,1+('0'arg(1)))
!rex: parse upper version !ver !vernum !verdate .; !brexx='BY'==!vernum; !kexx='KEXX'==!ver; !pcrexx='REXX/PERSONAL'==!ver|'REXX/PC'==!ver; !r4='REXX-R4'==!ver; !regina='REXX-REGINA'==left(!ver,11); !roo='REXX-ROO'==!ver; call !env; return
!sys:  !cms=!sys=='CMS'; !os2=!sys=='OS2'; !tso=!sys=='TSO'|!sys=='MVS'; !vse=!sys=='VSE'; !dos=pos('DOS',!sys)\==0|pos('WIN',!sys)\==0|!sys=='CMD'; !crx=left(!sys,6)=='DOSCRX'; call !rex; return
!var: call !fid; if !kexx then return space(dosenv(arg(1))); return space(value(arg(1),,!env))

Regina[edit]

The regina interpreter supports the rexxcurses plugin, which provides a facility to clear the screen (not shown here).

Scala[edit]

Library: Scala
object Cls extends App {print("\033[2J")}

Ring[edit]

system('clear')

Ruby[edit]

system 'clear'

Or, without reliance on the command line: (equivalent to `clear`)

puts "\e[H\e[2J"

Seed7[edit]

The function clear is portable and clears the console window. Clear is based on terminfo respectively the Windows console API. A portable function to clear cannot rely on shell respectively cmd.exe commands, because Windows uses CLS and Unix shells use CLEAR, to clear a screen. ANSI terminal escape sequences are also not 100% portable, since not all terminals accept them.

$ include "seed7_05.s7i";
include "console.s7i";
 
const proc: main is func
local
var text: console is STD_NULL;
begin
console := open(CONSOLE);
clear(console);
# 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[edit]

Using a cached-function:

func clear { print(static x = `clear`) };
clear();

Directly invoking the `clear` command:

Sys.run('clear');

Alternatively, without reliance on the command line:

print "\e[3J\e[H\e[2J";

Smalltalk[edit]

Transcript clear.

Tcl[edit]

This only works on systems with ANSI terminal handling, i.e., Unix platforms.

puts -nonewline "\033\[2J"
flush stdout

UNIX Shell[edit]

The clear command can be used to clear the terminal screen:

Works with: Bourne Shell
clear
 
# Alternative method using tput
tput clear

XPL0[edit]

code Clear=40;
Clear;

zkl[edit]

System.cmd(System.isWindows and "cls" or "clear");
// or, for ANSI terminals: print("\e[2J")