Console clear to end of line

Just starting out? Need help? Post your questions and find answers here.
User avatar
RichAlgeni
Addict
Addict
Posts: 914
Joined: Wed Sep 22, 2010 1:50 am
Location: Bradenton, FL

Console clear to end of line

Post by RichAlgeni »

Is there a way to clear the rest of a line in a Windows Console from the cursor position, without overwriting with spaces? With terminal emulators like vt100, there was an escape sequence you could print that would clear the rest of the line you were on. I was wondering if the console had anything like this.
Thanks!
Oso
Enthusiast
Enthusiast
Posts: 595
Joined: Wed Jul 20, 2022 10:09 am

Re: Console clear to end of line

Post by Oso »

RichAlgeni wrote: Fri Jan 20, 2023 5:40 pm Is there a way to clear the rest of a line in a Windows Console from the cursor position, without overwriting with spaces? With terminal emulators like vt100, there was an escape sequence you could print that would clear the rest of the line you were on. I was wondering if the console had anything like this.
Hi RichAlgeni, to the best of my knowledge, the Windows console is limited in terms of control, although there is a Windows API that provides access to more capabilities . There is also this page https://learn.microsoft.com/en-us/windo ... -sequences, entitled Console Virtual Terminal Sequences and it lists various VT100 escape codes. I'm unclear precisely what is meant by 'virtual terminal'. I tried some of the codes just now, without success.

The better option is likely to be the PureBasic graphical console (example below) which you may already be aware of. This gives you the ability to address the cursor position. The link https://www.purebasic.com/documentation ... index.html (where it indicates console.pb) provides a better example of this. I believe that you still need to generate spaces to clear existing text content however. I don't think that's normally a problem — it's very fast anyway.

Code: Select all

    OpenConsole()                                  ; First we must open a console
    ConsoleTitle ("PureBasic - Console Example:")  ; Now we can give the opened console a Titlename ;)
    EnableGraphicalConsole(1)
    ConsoleLocate (18,12)                          ; x y position
    Print ("Please enter your name:   ")           ; Ask for name
    name$=Input()                                  ; Wait for user input
    ClearConsole()     
I have just developed a console command line editor, providing full cursor movement, arrow keys, insert and delete functions and a clear to end of line, and that's how I did it — with spaces. It works very well, there's no discernible delay at all.
User avatar
RichAlgeni
Addict
Addict
Posts: 914
Joined: Wed Sep 22, 2010 1:50 am
Location: Bradenton, FL

Re: Console clear to end of line

Post by RichAlgeni »

Hi Oso! Thanks for the kind reply! That's what I thought, as I did find the code to determine the location of the cursor, but nothing about clearing the rest of a line.
Cheers!
Rich
User avatar
mk-soft
Always Here
Always Here
Posts: 5404
Joined: Fri May 12, 2006 6:51 pm
Location: Germany

Re: Console clear to end of line

Post by mk-soft »

Only with overwrite ...

Code: Select all

If OpenConsole()
  Print("Hello xxxxxxxxxxxxxxx")
  Print(#CR$ + Space(80) + #CR$)
  Print("World!")
  Input()
EndIf
My Projects ThreadToGUI / OOP-BaseClass / EventDesigner V3
PB v3.30 / v5.75 - OS Mac Mini OSX 10.xx - VM Window Pro / Linux Ubuntu
Downloads on my Webspace / OneDrive
Oso
Enthusiast
Enthusiast
Posts: 595
Joined: Wed Jul 20, 2022 10:09 am

Re: Console clear to end of line

Post by Oso »

RichAlgeni wrote: Fri Jan 20, 2023 11:04 pm Hi Oso! Thanks for the kind reply! That's what I thought, as I did find the code to determine the location of the cursor, but nothing about clearing the rest of a line. Cheers! Rich
I've figured it out RichAlgeni — I put the console into virtual terminal mode, which then supports ANSI VT100 standard codes. It took me a while to understand what Microsoft's documentation meant by 'virtual terminal', but I got there in the end. Microsoft's documentation is written in a pretentious and inaccessible way which limits its value to only those who are already familiar with it. Anyway, the code below gives a simple demonstration of cursor movement and clearing, from cursor to start-of-line, cursor to end-of-line, cursor to top-of-screen with a 3-second delay between each step so you can see what it's doing.

Code: Select all

Procedure Set_Up_Console()
  
  Define handle.i
   
  OpenConsole()

  handle = GetStdHandle_(#STD_OUTPUT_HANDLE)
  SetConsoleMode_(handle, 5)
  
  For a=1 To 15
    PrintN( "This is test line " + Str(a))
  Next a
  Print("And finally, line 16 after which we'll clear to start-of-line")
  Delay(3000)
  
  Print(#ESC$ + "[1K");  * Clear from cursor to start of line
  Delay(3000)
  
  Print(#CR$)
  Print("Display line again and move cursor to start of line")
  Print(#CR$)
  Delay(3000)
  
  Print(#ESC$ + "[0K");  * Clear from cursor to end of line

  Delay(3000)
  Print(#ESC$ + "[3A");  * Move up 3 lines
  Delay(3000)
  
  Print(#ESC$ + "[0K");  * Clear from cursor to end of line
  Print(#ESC$ + "[1J");  * Clear up from cursor to top of screen  
  
  Delay(3000)
  
  Print(#ESC$ + "[J");   * Clear from cursor to end of screen
  Delay(3000)

  PrintN("Now we're displaying conventionally...")
  Delay(3000)
    
EndProcedure

Set_Up_Console()
Below is a list of VT100 codes reproduced from https://espterm.github.io/docs/VT100%20 ... codes.html although it isn't necessarily a list of functions supported in the Windows console.

Code: Select all

This document describes how to control a VT100 terminal. The entries are of the form "name, description, escape code".

The name isn't important, and the description is just to help you find what you're looking for. What you have to do is send the "escape code" to the screen. These codes are often several characters long, but they all begin with ^[. This isn't the two characters ^ and [, but rather a representation of the ASCII code ESC (which is why these are called escape codes).

ESC has the decimal value 27 and should be sent before the rest of the code, which is simply an ASCII string.

As an example of how to use this information, here's how to clear the screen in C, using the VT100 escape codes:

    #define ASCII_ESC 27
    printf( "%c[2J", ASCII_ESC );

   or

    puts( "\033[2J" );

Name                  Description                            Esc Code

setnl LMN             Set new line mode                      ^[[20h
setappl DECCKM        Set cursor key to application          ^[[?1h
setansi DECANM        Set ANSI (versus VT52)                 none
setcol DECCOLM        Set number of columns to 132           ^[[?3h
setsmooth DECSCLM     Set smooth scrolling                   ^[[?4h
setrevscrn DECSCNM    Set reverse video on screen            ^[[?5h
setorgrel DECOM       Set origin to relative                 ^[[?6h
setwrap DECAWM        Set auto-wrap mode                     ^[[?7h
setrep DECARM         Set auto-repeat mode                   ^[[?8h
setinter DECINLM      Set interlacing mode                   ^[[?9h

setlf LMN             Set line feed mode                     ^[[20l
setcursor DECCKM      Set cursor key to cursor               ^[[?1l
setvt52 DECANM        Set VT52 (versus ANSI)                 ^[[?2l
resetcol DECCOLM      Set number of columns to 80            ^[[?3l
setjump DECSCLM       Set jump scrolling                     ^[[?4l
setnormscrn DECSCNM   Set normal video on screen             ^[[?5l
setorgabs DECOM       Set origin to absolute                 ^[[?6l
resetwrap DECAWM      Reset auto-wrap mode                   ^[[?7l
resetrep DECARM       Reset auto-repeat mode                 ^[[?8l
resetinter DECINLM    Reset interlacing mode                 ^[[?9l

altkeypad DECKPAM     Set alternate keypad mode              ^[=
numkeypad DECKPNM     Set numeric keypad mode                ^[>

setukg0               Set United Kingdom G0 character set    ^[(A
setukg1               Set United Kingdom G1 character set    ^[)A
setusg0               Set United States G0 character set     ^[(B
setusg1               Set United States G1 character set     ^[)B
setspecg0             Set G0 special chars. & line set       ^[(0
setspecg1             Set G1 special chars. & line set       ^[)0
setaltg0              Set G0 alternate character ROM         ^[(1
setaltg1              Set G1 alternate character ROM         ^[)1
setaltspecg0          Set G0 alt char ROM and spec. graphics ^[(2
setaltspecg1          Set G1 alt char ROM and spec. graphics ^[)2

setss2 SS2            Set single shift 2                     ^[N
setss3 SS3            Set single shift 3                     ^[O

modesoff SGR0         Turn off character attributes          ^[[m
modesoff SGR0         Turn off character attributes          ^[[0m
bold SGR1             Turn bold mode on                      ^[[1m
lowint SGR2           Turn low intensity mode on             ^[[2m
underline SGR4        Turn underline mode on                 ^[[4m
blink SGR5            Turn blinking mode on                  ^[[5m
reverse SGR7          Turn reverse video on                  ^[[7m
invisible SGR8        Turn invisible text mode on            ^[[8m

setwin DECSTBM        Set top and bottom line#s of a window  ^[[<v>;<v>r

cursorup(n) CUU       Move cursor up n lines                 ^[[<n>A
cursordn(n) CUD       Move cursor down n lines               ^[[<n>B
cursorrt(n) CUF       Move cursor right n lines              ^[[<n>C
cursorlf(n) CUB       Move cursor left n lines               ^[[<n>D
cursorhome            Move cursor to upper left corner       ^[[H
cursorhome            Move cursor to upper left corner       ^[[;H
cursorpos(v,h) CUP    Move cursor to screen location v,h     ^[[<v>;<h>H
hvhome                Move cursor to upper left corner       ^[[f
hvhome                Move cursor to upper left corner       ^[[;f
hvpos(v,h) CUP        Move cursor to screen location v,h     ^[[<v>;<h>f
index IND             Move/scroll window up one line         ^[D
revindex RI           Move/scroll window down one line       ^[M
nextline NEL          Move to next line                      ^[E
savecursor DECSC      Save cursor position and attributes    ^[7
restorecursor DECSC   Restore cursor position and attributes ^[8

tabset HTS            Set a tab at the current column        ^[H
tabclr TBC            Clear a tab at the current column      ^[[g
tabclr TBC            Clear a tab at the current column      ^[[0g
tabclrall TBC         Clear all tabs                         ^[[3g

dhtop DECDHL          Double-height letters, top half        ^[#3
dhbot DECDHL          Double-height letters, bottom half     ^[#4
swsh DECSWL           Single width, single height letters    ^[#5
dwsh DECDWL           Double width, single height letters    ^[#6

cleareol EL0          Clear line from cursor right           ^[[K
cleareol EL0          Clear line from cursor right           ^[[0K
clearbol EL1          Clear line from cursor left            ^[[1K
clearline EL2         Clear entire line                      ^[[2K

cleareos ED0          Clear screen from cursor down          ^[[J
cleareos ED0          Clear screen from cursor down          ^[[0J
clearbos ED1          Clear screen from cursor up            ^[[1J
clearscreen ED2       Clear entire screen                    ^[[2J

devstat DSR           Device status report                   ^[5n
termok DSR               Response: terminal is OK            ^[0n
termnok DSR              Response: terminal is not OK        ^[3n

getcursor DSR         Get cursor position                    ^[6n
cursorpos CPR            Response: cursor is at v,h          ^[<v>;<h>R

ident DA              Identify what terminal type            ^[[c
ident DA              Identify what terminal type (another)  ^[[0c
gettype DA               Response: terminal type code n      ^[[?1;<n>0c

reset RIS             Reset terminal to initial state        ^[c

align DECALN          Screen alignment display               ^[#8
testpu DECTST         Confidence power up test               ^[[2;1y
testlb DECTST         Confidence loopback test               ^[[2;2y
testpurep DECTST      Repeat power up test                   ^[[2;9y
testlbrep DECTST      Repeat loopback test                   ^[[2;10y

ledsoff DECLL0        Turn off all four leds                 ^[[0q
led1 DECLL1           Turn on LED #1                         ^[[1q
led2 DECLL2           Turn on LED #2                         ^[[2q
led3 DECLL3           Turn on LED #3                         ^[[3q
led4 DECLL4           Turn on LED #4                         ^[[4q

#
#  All codes below are for use in VT52 compatibility mode.
#

setansi               Enter/exit ANSI mode (VT52)            ^[<

altkeypad             Enter alternate keypad mode            ^[=
numkeypad             Exit alternate keypad mode             ^[>

setgr                 Use special graphics character set     ^[F
resetgr               Use normal US/UK character set         ^[G

cursorup              Move cursor up one line                ^[A
cursordn              Move cursor down one line              ^[B
cursorrt              Move cursor right one char             ^[C
cursorlf              Move cursor left one char              ^[D
cursorhome            Move cursor to upper left corner       ^[H
cursorpos(v,h)        Move cursor to v,h location            ^[<v><h>
revindex              Generate a reverse line-feed           ^[I

cleareol              Erase to end of current line           ^[K
cleareos              Erase to end of screen                 ^[J

ident                 Identify what the terminal is          ^[Z
identresp             Correct response to ident              ^[/Z

#
# VT100 Special Key Codes
#
# These are sent from the terminal back to the computer when the
# particular key is pressed.  Note that the numeric keypad keys
# send different codes in numeric mode than in alternate mode.
# See escape codes above to change keypad mode.
#

# Function Keys:

PF1     ^[OP
PF2     ^[OQ
PF3     ^[OR
PF4     ^[OS

# Arrow Keys:
        Reset    Set
        -----    ---
up      ^[A ^[OA
down    ^[B ^[OB
right   ^[C ^[OC
left    ^[D ^[OD


# Numeric Keypad Keys:

        Keypad Mode
        -----------------
Keypad Key  Numeric Alternate
----------  ------- ---------
0       0   ^[Op
1       1   ^[Oq
2       2   ^[Or
3       3   ^[Os
4       4   ^[Ot
5       5   ^[Ou
6       6   ^[Ov
7       7   ^[Ow
8       8   ^[Ox
9       9   ^[Oy
- (minus)   -   ^[Om
, (comma)   ,   ^[Ol
. (period)  .   ^[On
ENTER       ^M  ^[OM

C 	27, 033, 0x1b
English 	27 decimal, 33 octal, 1b hexadecimal
Oso
Enthusiast
Enthusiast
Posts: 595
Joined: Wed Jul 20, 2022 10:09 am

Re: Console clear to end of line

Post by Oso »

There's also a list of colour codes, which it supports.

Code: Select all

Print(#ESC$ + "[31;46m")
The above would be 31 (red foreground characters) on 46 (cyan background)

Set Attribute Mode <ESC>[{attr1};...;{attrn}m

Sets multiple display attribute settings. The following lists standard attributes:

0 Reset all attributes
1 Bright
2 Dim
4 Underscore
5 Blink
7 Reverse
8 Hidden

Foreground Colours
30 Black
31 Red
32 Green
33 Yellow
34 Blue
35 Magenta
36 Cyan
37 White

Background Colours
40 Black
41 Red
42 Green
43 Yellow
44 Blue
45 Magenta
46 Cyan
47 White
User avatar
Mijikai
Addict
Addict
Posts: 1360
Joined: Sun Sep 11, 2016 2:17 pm

Re: Console clear to end of line

Post by Mijikai »

Thats pretty neat, thanks for sharing Oso, i did not know about that mode at all.
Oso
Enthusiast
Enthusiast
Posts: 595
Joined: Wed Jul 20, 2022 10:09 am

Re: Console clear to end of line

Post by Oso »

Mijikai wrote: Sat Jan 21, 2023 1:09 pm Thats pretty neat, thanks for sharing Oso, i did not know about that mode at all.
Thanks Mijikai, I'm pleased that you saw it. I nearly included a mention of the fact it was you who introduced me to the console API :D

I recall that in the MSDOS days, there was a file called ANSI.SYS. I was never sure what the file was for, though on reading today, I found that it provided support for those codes within the console — a long-standing function, presumably. Given these new capabilities, I've begun thinking about an old plan from college days, to redevelop WordStar :o

Image
User avatar
Mijikai
Addict
Addict
Posts: 1360
Joined: Sun Sep 11, 2016 2:17 pm

Re: Console clear to end of line

Post by Mijikai »

Oso wrote: Sat Jan 21, 2023 7:12 pm to redevelop WordStar :o
:lol:
I played around a bit, the Virtual Terminal mode its pretty cool.

Some more code for the Virtual Terminal mode:

Code: Select all

EnableExplicit

#ENABLE_VIRTUAL_TERMINAL_PROCESSING = $0004

Procedure.i VirtualConsoleHandler(Type.i);<- function to end gracefully
  Protected.i hout,mode
  If Type = #CTRL_CLOSE_EVENT
    hout = GetStdHandle_(#STD_OUTPUT_HANDLE)
    If hout <> #INVALID_HANDLE_VALUE
      If GetConsoleMode_(hout,@mode)
        SetConsoleMode_(hout,mode&~#ENABLE_VIRTUAL_TERMINAL_PROCESSING);<- restore the console
      EndIf
    EndIf
  EndIf
  ProcedureReturn #False;<- transfer control to the next handler
EndProcedure

Procedure.i OpenVirtualConsole(Title.s = #Null$)
  Protected.i hout,mode
  If OpenConsole(Title)
    hout = GetStdHandle_(#STD_OUTPUT_HANDLE)
    If hout <> #INVALID_HANDLE_VALUE
      If GetConsoleMode_(hout,@mode)
        If SetConsoleMode_(hout,mode|#ENABLE_VIRTUAL_TERMINAL_PROCESSING)
          If SetConsoleCtrlHandler_(@VirtualConsoleHandler(),#True)            
            ProcedureReturn #True
          EndIf
          SetConsoleMode_(hout,mode)
        EndIf
      EndIf
    EndIf
    CloseConsole()
  EndIf
  ProcedureReturn #False
EndProcedure

Procedure.i Main()
  If OpenVirtualConsole()
    Print(#ESC$ + "[37;46m")
    Print("Hello World!")
    Input()
    CloseConsole()
  EndIf
  ProcedureReturn #Null
EndProcedure

Main()

End
Oso
Enthusiast
Enthusiast
Posts: 595
Joined: Wed Jul 20, 2022 10:09 am

Re: Console clear to end of line

Post by Oso »

Mijikai wrote: Sun Jan 22, 2023 12:27 pm Some more code for the Virtual Terminal mode:

Code: Select all

#ENABLE_VIRTUAL_TERMINAL_PROCESSING = $0004
      If GetConsoleMode_(hout,@mode)
        SetConsoleMode_(hout,mode&~#ENABLE_VIRTUAL_TERMINAL_PROCESSING);<- restore the console
        .
        .
        If SetConsoleMode_(hout,mode|#ENABLE_VIRTUAL_TERMINAL_PROCESSING)
Thanks for sending this code Mijikai. I don't follow the syntax of the above though, especially mode&~ although I assume you're taking the existing mode and setting the additional bits. I tried $0004 when I was playing around with it yesterday, but it wouldn't work for me. I found that 5 and 7 worked.

The following also is new to me as you appear to be referencing the name of the procedure as its memory address.

Code: Select all

If SetConsoleCtrlHandler_(@VirtualConsoleHandler(),#True)
User avatar
Mijikai
Addict
Addict
Posts: 1360
Joined: Sun Sep 11, 2016 2:17 pm

Re: Console clear to end of line

Post by Mijikai »

&~ removes a flag with an and not bitwise operation while | combines them with an or operation.
The 5 or $0005 works because it is a combination of the flags #ENABLE_PROCESSED_OUTPUT and #ENABLE_VIRTUAL_TERMINAL_PROCESSING
#ENABLE_VIRTUAL_TERMINAL_PROCESSING requires the other flag to work.
The 7 encodes another combination of flags that include both required flags.

Code: Select all

#ENABLE_VIRTUAL_TERMINAL_PROCESSING = $0004
Debug #ENABLE_PROCESSED_OUTPUT | #ENABLE_VIRTUAL_TERMINAL_PROCESSING
PB already sets #ENABLE_PROCESSED_OUTPUT so it was enough to add the other flag.
Oso
Enthusiast
Enthusiast
Posts: 595
Joined: Wed Jul 20, 2022 10:09 am

Re: Console clear to end of line

Post by Oso »

Mijikai wrote: Sun Jan 22, 2023 3:53 pm &~ removes a flag with an and not bitwise operation while | combines them with an or operation.
The 5 or $0005 works because it is a combination of the flags #ENABLE_PROCESSED_OUTPUT and #ENABLE_VIRTUAL_TERMINAL_PROCESSING
#ENABLE_VIRTUAL_TERMINAL_PROCESSING requires the other flag to work.
Thanks Mijikai, in some respects, the interception of VT100 codes in the console is very simple. For instance I noticed it is using them to control settings which do not only affect the current console window, but other open console windows too.

I added the below to set a fixed cursor and I noticed that two other console windows that were already open before I even compiled the code, also changed at the same time :shock:

Code: Select all

Print(#ESC$ + "[?12l")       ; Set non-blinking cursor
One hopes that a cursor movement in one console window doesn't move the cursor in other console windows — joking of course.
User avatar
RichAlgeni
Addict
Addict
Posts: 914
Joined: Wed Sep 22, 2010 1:50 am
Location: Bradenton, FL

Re: Console clear to end of line

Post by RichAlgeni »

wrote:I've figured it out RichAlgeni — I put the console into virtual terminal mode, which then supports ANSI VT100 standard codes.
Nicely done my friend!!! Thanks for your efforts.

Rich
Oso
Enthusiast
Enthusiast
Posts: 595
Joined: Wed Jul 20, 2022 10:09 am

Re: Console clear to end of line

Post by Oso »

RichAlgeni wrote: Nicely done my friend!!! Thanks for your efforts.
Rich
Thanks for writing back, Rich. I'm glad you asked about it, it was a useful one to know.
User avatar
HeX0R
Addict
Addict
Posts: 992
Joined: Mon Sep 20, 2004 7:12 am
Location: Hell

Re: Console clear to end of line

Post by HeX0R »

You could also use this here and add a few things to your needs:
viewtopic.php?f=12&t=64556
Then it would be even cross platform.
Post Reply