Terminal control/Ringing the terminal bell: Difference between revisions

From Rosetta Code
Content added Content deleted
m (→‎{{header|Phix}}: syntax coloured)
Line 612: Line 612:


=={{header|Phix}}==
=={{header|Phix}}==
<lang Phix>puts(1,"\x07")</lang>
<!--<lang Phix>(phixonline)-->
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\x07"</span><span style="color: #0000FF;">)</span>
<!--</lang>-->
Ineffective under pwa/p2js - just displays an unknown character glyph.


=={{header|PHP}}==
=={{header|PHP}}==

Revision as of 09:09, 15 April 2022

Task
Terminal control/Ringing the terminal bell
You are encouraged to solve this task according to the task description, using any language you may know.


Task

Make the terminal running the program ring its "bell".


On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal.   It is usually used to indicate a problem where a wrong character has been typed.

In most terminals, if the   Bell character   (ASCII code 7,   \a in C)   is printed by the program, it will cause the terminal to ring its bell.   This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.

11l

<lang 11l>print("\a")</lang>

6800 Assembly

<lang m68k> .cr 6800

       .tf  bel6800.obj,AP1
       .lf  bel6800
=====================================================;
Ring the Bell for the Motorola 6800  ;
by barrym 2013-03-31  ;
-----------------------------------------------------;
Rings the bell of an ascii terminal (console)  ;
connected to a 1970s vintage SWTPC 6800 system,  ;
which is the target device for this assembly.  ;
Many thanks to
;
swtpc.com for hosting Michael Holley's documents! ;
sbprojects.com for a very nice assembler!  ;
swtpcemu.com for a very capable emulator!  ;
reg a holds the ascii char to be output  ;
-----------------------------------------------------;

outeee = $e1d1 ;ROM: console putchar routine

       .or  $0f00
-----------------------------------------------------;

main ldaa #7 ;Load the ascii BEL char

       jsr  outeee     ;  and print it
       swi             ;Return to the monitor
       .en</lang>

8086 Assembly

Using stdout

Translation of: X86 Assembly

This is how it's supposed to be done: <lang asm>.model small .stack 1024

.data

.code

start: mov ah, 02h ;character output

       mov     dl, 07h         ;bell code
       int     21h             ;call MS-DOS
       mov     ax, 4C00h       ;exit 
       int     21h             ;return to MS-DOS

end start</lang>

But I couldn't hear anything on DOSBox when doing this.

The hard way

This version takes direct control over the PC's beeper to produce a tone whenever BEL is passed to PrintChar. <lang asm>.model small .stack 1024

.data

.code

start:

mov al,7 call PrintChar

mov ax,4C00h int 21h ;return to DOS

PrintChar: ;Print AL to screen push cx push bx push ax cmp al,7 jne skipBEL call RingBell jmp done_PrintChar skipBEL: mov bl,15 ;text color will be white mov ah,0Eh int 10h ;prints ascii code stored in AL to the screen (this is a slightly different putc syscall) done_PrintChar: pop ax pop bx pop cx ret

RingBell: push ax push cx push dx

       ;if BEL is the argument passed to PrintChar, it will call this function and not actually print anything or advance the cursor
       ;this uses the built-in beeper to simulate a beep

mov al,10110110b ;select counter 2, 16-bit mode out 43h, al

mov ax,0C00h ;set pitch of beep - this is somewhat high but isn't too annoying. Feel free to adjust this value out 42h,al mov al,ah out 42h,al


mov al,3 out 61h,al ;enable sound and timer mode

mov cx,0FFFFh mov dx,0Fh ;set up loop counters

beepdelay: ;delay lasts about half a second loop beepdelay mov cx,0FFFFh dec dx jnz beepdelay

mov al,0 ;mute out 61h,al ;cut the sound

               ; mov bl,15
               ; mov ax,0E20h                  ;print a spacebar to the terminal
               ; int 10h                       ;uncomment these 3 lines if you want the BEL to "take up space" in the output stream

pop dx pop cx pop ax ret

end start</lang>

Action!

<lang Action!>PROC Wait(BYTE frames)

 BYTE RTCLOK=$14
 frames==+RTCLOK
 WHILE frames#RTCLOK DO OD

RETURN

PROC Main()

 BYTE
   i,n=[3],
   CH=$02FC ;Internal hardware value for last key pressed
 PrintF("Press any key to hear %B bells...",n)
 DO UNTIL CH#$FF OD
 CH=$FF
 FOR i=1 TO n
 DO
   Put(253) ;buzzer
   Wait(20)
 OD
 Wait(100)

RETURN</lang>

Output:

Screenshot from Atari 8-bit computer

Ada

<lang ada>with Ada.Text_IO; use Ada.Text_IO; with Ada.Characters.Latin_1;

procedure Bell is begin

  Put(Ada.Characters.Latin_1.BEL);

end Bell;</lang>

Applescript

<lang applescript>beep</lang>

Arturo

<lang rebol>print "\a"</lang>

Asymptote

<lang Asymptote>beep()</lang> See beep() in the Asymptote manual.

AutoHotkey

<lang AutoHotkey> fileappend, `a, * </lang>

This requires that you compile the exe in console mode (see Lexikos script to change this) or pipe the file through more: autohotkey bell.ahk |more

AWK

<lang awk>BEGIN { print "\a" # Ring the bell }</lang>

BASIC

Applesoft BASIC

<lang Applesoft BASIC> 10 PRINT CHR$ (7);</lang>

Integer BASIC

You can't see it, but the bell character (Control G) is embedded in what looks like an empty string on line 10. <lang Integer BASIC> 10 PRINT "";: REM ^G IN QUOTES

 20 END</lang>

IS-BASIC

<lang IS-BASIC>PING</lang>

Locomotive Basic

<lang locobasic>10 PRINT CHR$(7)</lang>

ZX Spectrum Basic

The ZX Spectrum had a speaker, rather than a bell. Here we use middle C as a bell tone, but we could produce a different note by changing the final zero to a different value.

<lang basic>BEEP 0.2,0</lang>

Batch File

Source: Here <lang dos>@echo off for /f %%. in ('forfiles /m "%~nx0" /c "cmd /c echo 0x07"') do set bell=%%. echo %bell%</lang>

BBC BASIC

Assuming that the platform the program is running on rings the bell when CHR$7 is sent to the VDU driver:

<lang bbcbasic>VDU 7</lang>

Bc

<lang Bc>print "\a"</lang>

beeswax

<lang beeswax>_7}</lang>

Befunge

<lang befunge>7,@</lang>

Bracmat

Run Bracmat in interactive mode (start Bracmat without command line arguments) and enter the following after the Bracmat prompt {?}: <lang bracmat>\a</lang> Alternatively, run Bracmat non-interactively. In DOS, you write

bracmat "put$\a"

In Linux, you do

bracmat 'put$\a'

Brainf***

Assuming the output stream is connected to a TTY, printing BEL should ring its bell.

<lang brainfuck> I

 +
+ +
+++

+-+-+

 .</lang>

C

<lang c>#include <stdio.h> int main() {

 printf("\a");
 return 0;

}</lang>

C#

Inside a function: <lang csharp>// the simple version: System.Console.Write("\a"); // will beep System.Threading.Thread.Sleep(1000); // will wait for 1 second System.Console.Beep(); // will beep a second time System.Threading.Thread.Sleep(1000);

// System.Console.Beep() also accepts (int)hertz and (int)duration in milliseconds: System.Console.Beep(440, 2000); // default "concert pitch" for 2 seconds </lang>

C++

<lang cpp>#include <iostream>

int main() {

 std::cout << "\a";
 return 0;

}</lang>

Clojure

<lang clojure>(println (char 7))</lang>

COBOL

Standard compliant: <lang cobol>DISPLAY SPACE WITH BELL</lang>

Works with: Visual COBOL

<lang cobol> IDENTIFICATION DIVISION.

      PROGRAM-ID. mf-bell.
      
      DATA DIVISION.
      WORKING-STORAGE SECTION.
      01  bell-code              PIC X USAGE COMP-X VALUE 22.
      01  dummy-param            PIC X.
      
      PROCEDURE DIVISION.
          CALL X"AF" USING bell-code, dummy-param
      
          GOBACK
          .</lang>

Common Lisp

<lang lisp> (format t "~C" (code-char 7)) </lang>

D

<lang d>void main() {

   import std.stdio;
   writeln('\a');

}</lang>

Delphi

<lang Delphi>program TerminalBell;

{$APPTYPE CONSOLE}

begin

 Writeln(#7);

end.</lang>

E

<lang e>print("\u0007")</lang>

Emacs Lisp

<lang lisp>(ding)  ;; ring the bell (beep)  ;; the same thing</lang> On a tty or in -batch mode this emits a BEL character. In a GUI it does whatever suits the window system. Variables visible-bell and ring-bell-function can control the behaviour.

beep was originally called feep, but that changed, recently :-)

Fri Dec 13 00:52:16 1985  Richard M. Stallman  (rms at prep)
	* subr.el: Rename feep to beep, a more traditional name.

F#

<lang fsharp>open System

Console.Beep()</lang>

Factor

<lang factor>USE: io

"\u{7}" print</lang>

Or:

<lang factor>USING: io strings ;

7 1string print</lang>

Forth

<lang forth>7 emit</lang>

Works with: GNU Forth

<lang forth>#bell emit</lang>

Works with: iForth

<lang forth>^G emit</lang>

FreeBASIC

<lang freebasic>' FB 1.05.0 Win64

Print !"\a" Sleep</lang>

gnuplot

<lang gnuplot>print "\007"</lang>

Go

<lang go>package main

import "fmt"

func main() {

 fmt.Print("\a")

}</lang>

Groovy

<lang groovy>println '\7'</lang>

Haskell

<lang haskell>main = putStr "\a"</lang>

Icon and Unicon

Works on both Icon and Unicon.

<lang Icon> procedure main ()

 write ("\7") # ASCII 7 rings the bell under Bash

end </lang>

J

This j sentence reads "Seven from alphabet." <lang J> 7{a. NB. noun a. is a complete ASCII ordered character vector.</lang>

Java

<lang java>public class Bell{

   public static void main(String[] args){
       java.awt.Toolkit.getDefaultToolkit().beep();
       //or
       System.out.println((char)7);
   }

}</lang>

Julia

Works with: Linux

<lang Julia> println("This should ring a bell.\a") </lang>

Output:
This should ring a bell.

And it does, provided that the bell is enabled on your terminal.

Kotlin

Works with: Windows version 10

<lang scala>// version 1.1.2

fun main(args: Array<String>) {

   println("\u0007")

}</lang>

Lasso

<lang Lasso>stdoutnl('\a')</lang>

<lang logo>type char 7</lang>

Lua

<lang lua>print("\a")</lang>

M2000 Interpreter

M2000 Environment has own console (not the one provided from system). Console used for graphics, and has 32 layers for text or and graphics and as sprites too. We can alter the console by code, moving to any monitor, changing font, font size and, line space. Also there is a split function, where the lower part can scroll, and the upper part used as header (we can write/draw in the upper part also, but CLS - clear screen- statement clear only the lower part).

Using Windows Bell

Async beep. If another start while beeps (it is a bell), then stop <lang M2000 Interpreter> Module CheckIt {

     After 300 {beep}
     Print "Begin"
     for i=0 to 100 {
           wait 10
           Print i
     }
     Print "End"

} CheckIt </lang>


Play tone at 1khz or specific hz

Execution stop to play tone

Tone (1khz)
Tone 200 (1 kgz 200 ms)
Tone 200, 5000 (5khz. 200ms)

<lang M2000 Interpreter> Module CheckIt {

     After 300 {Tone 200}
     Print "Begin"
     for i=0 to 100 {
           wait 10
           Print i
     }
     Print "End"

} CheckIt </lang>


Play melody with beeper

Execution stop to play tune

Tune melody$
Tune duration_per_note, melody$

<lang M2000 Interpreter> Module CheckIt {

     After 300 {Tune 300, "C3BC#"}
     Print "Begin"
     for i=0 to 100 {
           wait 10
           Print i
     }
     Print "End"

} CheckIt </lang>


using midi to send music scores

Play a score in each of 16 voices (async, programming internal midi, problem with async in Wine Linux). We can make a piano using keyboard and play/score commands.

<lang M2000 Interpreter> Module CheckIt {

     Score 1, 500, "c@2dc @2ef"
     Play 1, 19  ' attach a music score to an organ
     Print "Begin"
     for i=0 to 100 {
           wait 10
           Print i
     }
     Print "End"
     \\ stop play, remove this and music continue, in console prompt
     Play 0

} CheckIt </lang>

There are other statements like Sound, and Background filename$ to play background music.

Mathematica/Wolfram Language

<lang Mathematica>Print["\007"]</lang>

MUMPS

<lang MUMPS>write $char(7)</lang>

Nanoquery

<lang Nanoquery>print chr(7)</lang>

Nemerle

<lang Nemerle>using System.Console;

module Beep {

   Main() : void
   {
       Write("\a");
       System.Threading.Thread.Sleep(1000);
       Beep();
       System.Threading.Thread.Sleep(1000);
       Beep(2600, 1000); // limited OS support
   }

}</lang>

NetRexx

<lang NetRexx>/* NetRexx */ options replace format comments java crossref symbols binary

runSample(arg) return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method runSample(arg) private static

 do
   BEL = 8x07
   jtk = java.awt.toolkit.getDefaultToolkit()
   say 'Bing!'(Rexx BEL).d2c
   Thread.sleep(500)
   say 'Ding\x07-ding\u0007!'
   Thread.sleep(500)
   say 'Beep!'
   jtk.beep()
 catch ex = Exception
   ex.printStackTrace()
 end
 return

</lang>

Nim

<lang nim>echo "\a"</lang>

Objeck

<lang objeck>7->As(Char)->PrintLine();</lang>

PARI/GP

Works with: PARI/GP version 2.7.4 and above

<lang parigp>\\ Ringing the terminal bell. \\ 8/14/2016 aev Strchr(7) \\ press <Enter></lang>

or

<lang parigp>print(Strchr(7)); \\ press <Enter></lang>

Output:
(11:12) gp > Strchr(7) \\ press <Enter>
%6 = ""
(11:13) gp > print(Strchr(7)); \\ press <Enter>

(11:14) gp >

Pascal

See Delphi

Perl

<lang perl>print "\a";</lang>

Phix

puts(1,"\x07")

Ineffective under pwa/p2js - just displays an unknown character glyph.

PHP

<lang php><?php echo "\007";</lang>

PicoLisp

<lang PicoLisp>(beep)</lang>

PL/I

<lang pli> declare bell character (1);

  unspec (bell) = '00000111'b;
  put edit (bell) (a);</lang>

PostScript

The following will only work in a PostScript interpreter that sends output to a terminal. It will very likely not make a printer beep. <lang postscript>(\007) print</lang>

PowerShell

One can either use the ASCII BEL character which only works in a console (i.e. not in a graphical PowerShell host such as PowerShell ISE): <lang powershell>"`a"</lang> or use the .NET Console class which works independent of the host application: <lang powershell>[Console]::Beep()</lang>

PureBasic

<lang PureBasic>Print(#BEL$)</lang>

Python

In Python 2.7.x: <lang python>print "\a"</lang> In Python 3.x: <lang python>print("\a")</lang>

Quackery

On some platforms the bell will not ring until the output buffer is flushed e.g. by a cr/lf.

<lang Quackery>ding</lang>

R

<lang R>alarm()</lang>

Racket

<lang racket>

  1. lang racket

(require (planet neil/charterm:3:0)) (with-charterm

(void (charterm-bell)))

</lang>

Raku

(formerly Perl 6) <lang perl6>print 7.chr;</lang>

Retro

<lang Retro>7 putc</lang>

REXX

There is no standard REXX built-in function to handle the sounding of the bell or a PC's speaker.

However, some REXX interpreters have added a non-standard BIF. <lang rexx>/*REXX program illustrates methods to ring the terminal bell or use the PC speaker. */

                    /*╔═══════════════════════════════════════════════════════════════╗
                      ║                                                               ║
                      ║  Note that the  hexadecimal code  to ring the  terminal bell  ║
                      ║  is different on an ASCII machine than an EBCDIC machine.     ║
                      ║                                                               ║
                      ║  On an  ASCII machine,  it is  (hexadecimal)  '07'x.          ║
                      ║   "  " EBCDIC    "       "  "        "        '2F'x.          ║
                      ║                                                               ║
                      ╚═══════════════════════════════════════════════════════════════╝*/

if 3=='F3' then bell= '2f'x /*we are running on an EBCDIC machine. */

           else bell= '07'x                     /* "  "     "     "  "  ASCII    "     */

say bell /*sound the bell on the terminal. */ say copies(bell, 20) /*as above, but much more annoying. */

                    /*╔═══════════════════════════════════════════════════════════════╗
                      ║                                                               ║
                      ║  Some REXX interpreters have a  built-in function  (BIF)  to  ║
                      ║  to produce a sound on the PC speaker, the sound is specified ║
                      ║  by frequency  and  an optional  duration.                    ║
                      ║                                                               ║
                      ╚═══════════════════════════════════════════════════════════════╝*/
                                        /* [↓]  supported by Regina REXX:              */

freq= 1200 /*frequency in (nearest) cycles per second. */ call beep freq /*sounds the PC speaker, duration= 1 second.*/ ms= 500 /*duration in milliseconds. */ call beep freq, ms /* " " " " " 1/2 " */


                                        /* [↓]  supported by PC/REXX  &  Personal REXX:*/

freq= 2000 /*frequency in (nearest) cycles per second. */ call sound freq /*sounds PC speaker, duration= .2 second. */ secs= .333 /*duration in seconds (round to nearest tenth).*/ call sound freq, secs /* " " " " 3/10 " */

                                        /*stick a fork in it, we're done making noises.*/</lang>

Ring

<lang ring> see char(7) </lang>

Ruby

<lang ruby>print "\a"</lang>

Rust

<lang rust>fn main() {

   print!("\x07");

}</lang>

Scala

<lang scala>java.awt.Toolkit.getDefaultToolkit().beep()</lang>

Seed7

<lang seed7>$ include "seed7_05.s7i";

const proc: main is func

 begin
   write("\a");
 end func;</lang>

Sidef

<lang ruby>print "\a";</lang>

SNUSP

<lang snusp>$+++++++.#</lang>

Standard ML

<lang sml>val () = print "\a"</lang>

Tcl

<lang tcl>puts -nonewline "\a";flush stdout</lang>

UNIX Shell

Works with: Bourne Shell
Works with: bash

<lang sh>#!/bin/sh

  1. Ring the terminal bell
  2. echo "\a" # does not work in some shells

tput bel</lang>

Wren

<lang ecmascript>System.print("\a")</lang>

X86 Assembly

<lang X86 Assembly>;Assemble with: tasm; tlink /t

       .model  tiny
       .code
       org     100h            ;.com files start here

start: mov ah, 02h ;character output

       mov     dl, 07h         ;bell code
       int     21h             ;call MS-DOS
       ret                     ;return to MS-DOS
       end     start</lang>

XPL0

<lang XPL0>code ChOut=8; ChOut(0,7)</lang>

zkl

<lang zkl>print("\x07");</lang>