Console Mode Pascal: changes

Revision 1663
Jwdietrich,
/* PascalScripts */
Older edit
Revision 1692 (current)
Alextp,
/* Output CJK text in Windows console */
@@ -1,45 +1,41 @@
1---
2categories:
3 - "Tutorials"
4 - "FPC"
5 - "Lazarus"
6 - "PascalScript"
7---
8
9::tpl[Console Mode Pascal]1::tpl[Console Mode Pascal]
102
11## Console-Mode Pascal Programming3## Console-Mode Pascal Programming
124
13Many of us were writing Pascal programs long before Graphic User Interfaces (GUIs) and Integrated Development Environments (IDEs) became fashionable. Many others are beginners at Pascal programming and need to be able to try out the basic tools of the language. Still others need to write console- or text-mode applications in order to perform complex system control tasks.5Many of us were writing [[Pascal]] [[Program|programs]] long before [[Graphical User Interface|Graphical User Interfaces]] (GUIs) and [[IDE|Integrated Development Environments (IDEs)]] became fashionable. Many others are beginners at Pascal programming and need to be able to try out the basic tools of the language. Still others need to write [[Command-line interface|console]]- or [[Text User Interface|text-mode]] applications in order to perform complex system control tasks.
146
15### Console mode programming without Lazarus7### Console mode programming without Lazarus
168
17Even though many prefer to use the Lazarus IDE to write console mode programs, you can also write them with any text editor and compile them yourself by calling the FPC compiler, e.g. this for a program in example.pas:9Even though many prefer to use the [[Lazarus IDE]] to write console mode programs, you can also write them with any text editor and compile them yourself by calling the [[FPC]] [[Compiler|compiler]], e.g. this for a program in example.pas:
1810
19```bash11```bash
20fpc example.pas12fpc example.pas
21```13```
2214
23Also, the text mode *fp* IDE (looks a bit like old Turbo Pascal) is available.15Also, the text mode *fp* IDE (looks a bit like old [[Turbo Pascal]]) is available.
24In the next sections we will focus on programming with Lazarus.16In the next sections we will focus on programming with [[Lazarus]].
2517
26### Console mode programming with Lazarus18### Console mode programming with Lazarus
2719
28Lazarus provides an ideal environment for learning Pascal, and for developing text-mode programs. All the functionality of the Integrated Development Environment can be used, including the Source Editor with its syntax highlighting, access to the libraries, complex searching and code completion tools, and syntax checking. If you don't want a Form with its visual components, you don't need one, but the Lazarus Source Editor is still a great environment for program development. You can compile and run your program during development, without ever leaving the Editor.20Lazarus provides an ideal environment for learning Pascal, and for developing text-mode programs. All the functionality of the Integrated Development Environment can be used, including the Source Editor with its [[Syntax highlighting|syntax highlighting]], access to the libraries, complex searching and code completion tools, and syntax checking. If you do not want a [[TForm|Form]] with its visual components, you do not need one, but the Lazarus Source Editor is still a great environment for program development. You can compile and run your program during development, without ever leaving the Editor.
2921
30To start a console-mode program, go to the Main Menu and select Project -> New Project and then select either **Program** or **Console Application**. The IDE will not generate all the extra files associated with a full graphic application, and will not open an Object Inspector box, but will open the Source Editor with a skeleton program structure and await your programming input.22To start a console-mode program, go to the Main Menu and select Project -> New Project and then select either **Program** or **Console Application**. The IDE will not generate all the extra files associated with a full graphic application, and will not open an Object Inspector box, but will open the Source Editor with a skeleton program structure and await your programming input.
3123
32:::note24:::note
33Under Windows a GUI application has no console and thus can not **writeln** or **readln**. You will get *File not open* errors. Disable under *Project Options / Compiler Options / Linking / Target specific options / Win32 GUI application* to create a console application.25Under Windows a GUI application has no console and thus can not **writeln** or **readln**. You will get *File not open* errors. Disable under *Project Options / Compiler Options / Linking / Target specific options / Win32 GUI application* to create a console application. In Lazarus IDE 1.4, this is under *Project(menu) / Project Options / Compiler Options / Config and Target / Target specific options / Win32 GUI application*.
34:::26:::
3527
28:::note
29Lazarus has some functionality for command line programs, such as [[CopyFile|copyfile]]. To use these, add a project requirement for LazUtils, which will not pull in the entire LCL. Then add the relevant unit to your uses clause.
30:::
31
36#### Project type: Console Application32#### Project type: Console Application
3733
38Selecting this project type in Lazarus creates a program with a new class derived from TCustomApplication. TCustomApplication provides a lot of the common things and makes programming command line utilities easy. For example checking command line options, writing help, checking environment variables and exception handling. All LCL programs use this automatically.34Selecting this project type in Lazarus creates a program with a new class derived from TCustomApplication. TCustomApplication provides a lot of the common things and makes programming command line utilities easy. For example checking command line options, writing help, checking [[Command_line_parameters_and_environment_variables#Environment_variables|environment variables]] and [[Exceptions|exception]] handling. All [[LCL]] programs use this automatically.
3935
40#### Project type: Program36#### Project type: Program
4137
42As a demonstration, we will write a very minimalistic Pascal program. In the IDE, select the 'Program' project type and let the IDE helps you a bit. For example when you add another unit the IDE will automatically add the unitname to the program uses section. This behavior is defined in the project options. So you can go between 'Program' and 'Custom Program' at any time.38As a demonstration, we will write a very minimalistic Pascal program. In the IDE, select the 'Program' project type and let the IDE helps you a bit. For example when you add another [[Unit|unit]] the IDE will automatically add the unitname to the program [[Uses|uses]] section. This behavior is defined in the project options. So you can go between 'Program' and 'Custom Program' at any time.
4339
44An example for complete beginners:40An example for complete beginners:
4541
@@ -57,21 +53,25 @@
57end.53end.
58```54```
5955
60### PascalScripts56### Pascal scripts
6157
62Additionally, it is possible to write [[Category:PascalScript|PascalScripts]] that are dynamically compiled by [[InstantFPC]], a cross-platform solution to run small Pascal programs as scripts. The shebang58Additionally, it is possible to write scripts that are dynamically compiled by [[InstantFPC]], a cross-platform solution to run (small) Pascal programs as scripts. The shebang
6359
64```60```
65#!/usr/bin/env instantfpc61#!/usr/bin/env instantfpc
66```62```
6763
68permits to start the script like a stand-alone application.64permits to start the script like a stand-alone program.
6965
66:::note
67Though it is used to run Pascal scripts, InstantFPC uses regular Object Pascal, not the PascalScript script language. So "**PascalScript**" and **Pascal script** are not the same.
68:::
69
70## Running a Program70## Running a Program
7171
72#### Compile72#### Compile
7373
74When you have finished your program (or program fragment) you can compile and run it by selecting Run -> Build (or Quick Compile) from the Main Menu or clicking on the Green (Run) triangle symbol in the Button Bar. Any compiler messages (warnings, progress reports or error messages) will appear in the Message Box, and hopefully there will eventually be a message to say74When you have finished your program (or program fragment) you can compile and run it by selecting Run -> Build (or Quick Compile) from the Main Menu or clicking on the Green (Run) triangle symbol ![](/_files/Start.png) in the Button Bar. Any compiler messages (warnings, progress reports or error messages) will appear in the Message Box, and hopefully there will eventually be a message to say
7575
76'Project "Project1" successfully built.:)'.76'Project "Project1" successfully built.:)'.
7777
@@ -83,7 +83,7 @@
8383
84#### Run in Console84#### Run in Console
8585
86You can execute the program by going to a console (terminal) window, then use **cd** to change to the directory and typing the name of the program. On Unix/Linux, if it is in the current directory you will have to start with ./ as the program probably won't be found in the PATH.86You can execute the program by going to a console (terminal) window, then use **cd** to change to the directory and typing the name of the program. On Unix/Linux, if it is in the current directory you will have to start with ./ as the program will probably not be found in the PATH.
8787
88Example for Linux/Unix where a program is stored in /tmp:88Example for Linux/Unix where a program is stored in /tmp:
8989
@@ -96,6 +96,10 @@
9696
97#### Run in IDE97#### Run in IDE
9898
99In internal console: show in the terminal output window.
100
101In redirect output.
102
99From the Main Menu, select Run -> Run Parameters, then check the box for "Use launching application". The first time you do this and try the Compile/Run sequence, you will probably get a rude message saying:103From the Main Menu, select Run -> Run Parameters, then check the box for "Use launching application". The first time you do this and try the Compile/Run sequence, you will probably get a rude message saying:
100104
101```105```
@@ -106,8 +110,10 @@
106110
107After your program has finished execution, a message "Press enter" appears on the screen. Thus any output your program generated will remain on the screen until you have had a chance to read it; after you press 'enter' the console window closes.111After your program has finished execution, a message "Press enter" appears on the screen. Thus any output your program generated will remain on the screen until you have had a chance to read it; after you press 'enter' the console window closes.
108112
109Unfortunately, this method doesn't allow you to use the integrated debugger.113On Linux, if the above message "xterm: Can't execvp /usr/share/lazarus//tools/runwait.sh: Permission denied" does not appear after checking the box for "Use launching application", type `/usr/bin/xterm $(TargetCmdLine)` and check `Use launching application` (xterm is installed on almost all Linux systems).
110114
115Unfortunately, this method does not allow you to use the integrated debugger.
116
111#### Run in IDE with redirected output117#### Run in IDE with redirected output
112118
113If you want to see what is written to stdout and want to use the integrated debugger as well, stdout can be redirected to a file with the following code:119If you want to see what is written to stdout and want to use the integrated debugger as well, stdout can be redirected to a file with the following code:
@@ -137,20 +143,15 @@
137end.143end.
138```144```
139145
140Output.txt can then be viewed with 'tail -f output.txt' or viewed with an editor if 'tail' is not available on your os.146Output.txt can then be viewed with 'tail -f output.txt' or viewed with an editor if 'tail' is not available on your [[Operating System|os]].
141147
142Alternatively, using Lazarus 0.9.31 or up (on Linux only): In the "View" menu, under "Debug Windows" there is an entry for a "console output" to view stdout148Alternatively, using Lazarus 0.9.31 or up (on Linux only): In the "View" menu, under "Debug Windows" there is an entry for a "console output" to view stdout
143149
144## Unicode (UTF8) output150## Unicode (UTF8) output
145151
146If you want your console mode program to show Unicode (UTF8) output on Windows Vista and higher (and perhaps on earlier versions, too), you can use the **SetConsoleOutputCP** command to set the console to the UTF8 character set.152If you want your console mode program to show Unicode ([[UTF-8|UTF8]]) output on Windows Vista and higher (and perhaps on earlier versions, too), you can use the **SetConsoleOutputCP** command to set the console to the UTF8 character set.
147153
148:::note154:::note
149After the program is done, the console behaves strangely on my system: entering commands and enter gives no result: no command executed, no error, nothing. Perhaps the console needs to be switched back? I tried that too, but it seemed to give the same result.
150\--[[User:BigChimp|BigChimp]] 17:15, 28 June 2012 (UTC)
151:::
152
153:::note
154you will need to make sure the font of the console can show the letters you want to output (e.g. Greek, Cyrillic, Korean).155you will need to make sure the font of the console can show the letters you want to output (e.g. Greek, Cyrillic, Korean).
155:::156:::
156157
@@ -191,18 +192,53 @@
191{$ENDIF}192{$ENDIF}
192UTF8TestString:= 'rosé, водка and ούζο';193UTF8TestString:= 'rosé, водка and ούζο';
193writeln ('plain: ' + UTF8TestString);194writeln ('plain: ' + UTF8TestString);
194{Apparently we don't need UTF8ToConsole for this195{Apparently we do not need UTF8ToConsole for this
195UTF8ToConsole did not do anything for me in fact.}196UTF8ToConsole did not do anything for me in fact.}
196end.197end.
197```198```
198199
200### Output CJK text in Windows console
201
202This example from forum member **Thaddy** shows how to properly setup Windows console to support CJK text.
203
204```pascal
205{$mode delphiunicode}{$H+}
206{$codepage utf8}
207uses Windows, SysUtils;
208var
209 s3, s1, s2: string;
210 var
211 cfi: CONSOLE_FONT_INFOEX;
212begin
213 cfi.cbSize := SizeOf(cfi);
214 cfi.nFont := 0;
215 cfi.dwFontSize.X := 0;
216 cfi.dwFontSize.Y := 20;
217 cfi.FontFamily := FF_DONTCARE;
218 cfi.FontWeight := FW_NORMAL;
219 // two fonts that support Chinese etc.
220 cfi.Facename := 'NSimSun';
221 // cfi.FaceName := 'SimSun-extB'; // this is a raster font.
222
223 SetTextCodePage(Output, CP_UTF8);
224 SetConsoleOutputCP(CP_UTF8);
225 SetCurrentConsoleFontEx(GetStdHandle(STD_OUTPUT_HANDLE), False, @cfi);
226
227 s1 := '春夏';
228 s2 := '秋冬';
229 s3 := s1+s2;
230 Writeln('s1=', s1,' s2=', s2, ' s3=', s3);
231 Readln;
232end.
233```
234
199## Examples235## Examples
200236
201You can use the Lazarus editor to try out all the examples in the standard Pascal textbooks, or you can write your own. Some of the most useful procedures are those for executing system commands or for running other programs (whether written in Pascal, C or Perl, or shell or batch scripts).237You can use the Lazarus editor to try out all the examples in the standard Pascal textbooks, or you can write your own. Some of the most useful procedures are those for executing system commands or for running other programs (whether written in Pascal, C or Perl, or shell or batch scripts).
202238
203#### Execute shell command239#### Execute shell command
204240
205Here is an example for a *Custom Program* or *Program*... that is Linux/Unix/OSX specific though:241Here is an example for a *Custom Program* or *Program*... that is Linux/Unix/macOS specific though:
206242
207```pascal243```pascal
208program TryShell;244program TryShell;
@@ -227,10 +263,10 @@
227var 263var
228 S: LongInt;264 S: LongInt;
229begin 265begin
230 S := fpsystem('cd /usr/local/src/fpc/devel/fpc ; make clean');266 S := fpsystem('cd /usr/local/src/fpc/devel/fpc ; make clean');
231 S := fpsystem('cd /usr/local/src/fpc/devel/lazarus ; make clean');267 S := fpsystem('cd /usr/local/src/fpc/devel/lazarus ; make clean');
232 S := fpsystem('cd /usr/local/src/fpc/devel ; svn update fpc >& ~/cvscheckout.log');268 S := fpsystem('cd /usr/local/src/fpc/devel ; svn update fpc >& ~/cvscheckout.log');
233 S := fpsystem('cd /usr/local/src/fpc/devel ; svn update lazarus >& ~/cvslaz.log');269 S := fpsystem('cd /usr/local/src/fpc/devel ; svn update lazarus >& ~/cvslaz.log' );
234end.270end.
235```271```
236272
@@ -246,9 +282,9 @@
246fpsystem ('do something in that subdirectory');282fpsystem ('do something in that subdirectory');
247```283```
248284
249doesn't work, because after each fpsystem function call the execution of the program returns to the directory it started in; so we need to include multiple statements per line within our calls to shell.285does not work, because after each **fpsystem()** [[Function|function]] call the execution of the program returns to the directory it started in; so we need to include multiple statements per line within our calls to shell via **fpsystem()**. \[Rather: it always starts in . \]
250286
251Of course, you don't have to enter every command as a separate line of Pascal; you could create a script file like this (from [[buildfaq]]):287One does not have to enter every command as a separate line of Pascal; one could create a **bash** script file like this (from [[buildfaq]]):
252288
253```bash289```bash
254#!/bin/sh290#!/bin/sh
@@ -263,9 +299,10 @@
263svn up lazarus >& ~/cvslaz.log299svn up lazarus >& ~/cvslaz.log
264```300```
265301
266Name it updatelaz.sh, and then call it from a Pascal program thus:302Name it **updatelaz.sh**, and then instead of using **bash** to execute it directly, call it from a Pascal program thus:
267303
268```pascal304```pascal
305(* This can be compiled or used as a Pascal script *)
269program LazUpdate1;306program LazUpdate1;
270uses 307uses
271 Classes, Unix;308 Classes, Unix;