Chapter 7: Working with Text

Introduction

Working With String Data Types

Searching for strings

How to Convert Numbers to Strings and Back

Converting a Number to a String

Converting Other Data Types

How to Read ASCII Text Files

Using a File Import Program

Writing ASCII Files to Disk

Using a Text Export Program

Conclusion

 

Introduction

If you have ever had to edit large amounts of text in a drawing, you have encountered one of AutoCAD's most frustrating limitations. While AutoCAD's text handling capabilities is one of it's strong points, it still leaves much to be desired where editing text is concerned. Fortunately AutoLISP can be of great help where text is concerned. In this chapter, you will look at the many functions that AutoLISP offers in the way of text or string manipulation. You will also look at how textural information can be store and retrieved from a file on disk and how data can be converted to and from string data types.

 

Working With String Data Types

In earlier versions of AutoCAD, editing text was a tedious task. You have to use the Change command to select a text line, then press return several times before you can actually make changes to the text. Even then, you would have to re-enter the entire line of text just to change one word. The text editing features of AutoCAD have come a long way and it doesn't take the same painful effort it once did. The following program is a simple line editor which simplifies the task of editing a single line of text. It was designed for the older versions of AutoCAD before the Ddmodify and Ddedit commands were available. While its function may be a bit outdated, it will serve to demonstrate how to handle text in AutoLISP.

 

Searching for Strings

The program Chtxt shown in figure 7.1 is a simple line editor. It uses AutoLISPs string handling functions to locate a specific string, then it replaces that string with another one specified by the user.

Open a file called chtxt.lsp and copy the program shown in figure 7.1 into the file. Save and close this file and open a new AutoCAD file called Chapt7.

 


;function to find text string from text entity-------------------------------
(defun gettxt ()
(setvar "osmode" 64)                                ;set osnap to insert
(setq pt1 (getpoint "\nPick text to edit: "))       ;get point on text
(Setvar "osmode" 0)                                 ;set osnap back to zero
(setq oldobj (entget (ssname (ssget pt1) 0) ))      ;get entity zero from prop.
(setq txtstr (assoc 1 oldobj))                      ;get list containing string
(cdr txtstr)                                        ;extract string from prop.
)
 
;function to update text string of text entity-------------------------------
(defun revtxt ()
(setq newtxt (cons 1 newtxt))                       ;create replacement propty.
(entmod (subst newtxt txtstr oldobj))               ;update database
)
 
;program to edit single line of text-----------------------------------------
(defun C:CHTXT (/ count oldstr newstr osleng otleng oldt old1
                  old2 newtxt pt1 oldobj txtstr oldtxt)
(setq count 0)                                      ;setup counter to zero
(setq oldtxt (gettxt))                              ;get old string from text
(setq otleng (strlen oldtxt))                       ;find length of old string
(setq oldstr (getstring T "\nEnter old string "))   ;get string to change
(Setq newstr (getstring T "\nEnter new string "))   ;get replacement string
(setq osleng (strlen oldstr))                       ;find length of substring-
  ;while string to replace is not found, do...       to be replaced
  (while (and (/= oldstr oldt)(<= count otleng))
    (setq count (1+ count))                         ;add 1 to counter
    (setq oldt (substr oldtxt count osleng))        ;get substring to compare
  );end WHILE
  ;if counting stops before end of old string is reached...
  (if (<= count otleng)
        (progn
           (setq old1 (substr oldtxt 1 (1- count))) ;get 1st half of old string
           (setq old2 (substr oldtxt (+ count osleng) otleng));get 2nd half
           (setq newtxt (strcat old1 newstr old2))  ;combine to make new string
           (revtxt)                                 ;update drawing
        )
        (princ "\nNo matching string found.")       ;else print message
  );end IF
(PRINC)
);END C:EDTXT
 

Figure 7.1: The Chtxt.lsp file

 

Load the Chtxt.lsp file and do the following steps:

 1. Use the Dtext command and write the following line of text:

For want of a battle, the kingdom was lost.

2. Enter Chtxt

3. At the prompt:

Pick text to edit:

pick the text you just entered. Note that the osnap cursor appears.

4. At the next prompt:

Enter old string:

enter the word battle in lower case letters.

5. At the next prompt:

Enter new string:

enter the word nail.

The text changes to read:

For want of a nail, the kingdom was lost.

In the C:CHTXT program, you are able to change a group of letters in a line of text without having to enter entire line over again. Also, you don't have to go through a series of unneeded prompts as you do with the change command. The following describes what C:CHTXT goes through to accomplish this.

The C:CHTXT program starts out with a user defined function called gettxt.

(defun C:EDTXT (/ count oldstr newstr osleng otleng oldt old1

old2 newtxt pt1 oldobj txtstr oldtxt)

(setq count 0)

(setq oldtxt (gettxt))

Gettxt prompts you to select the text to be edited. It then extracts from the drawing database the text string associated with that text. The extracted text is assigned to the symbol oldtxt. We will look at this extraction process in Chapter--- but for now, think of the gettxt function as a function for getting text.

In the next line of the Chtxt program, we see a new function strlen:

(setq otleng (strlen oldtxt))

Strlen finds the number of characters in a string.

The syntax for strlen is:

(strlen [string or string variable])

Strlen returns an integer value representing the number of characters found in its arguments. Blank spaces are counted as characters. In the above expression, the value found by strlen is assigned to the variable otleng.

The next two expressions obtain from the user the old portion of the text to be replace and the replacement text.

(setq oldstr (getstring T "\nEnter old string "))

(Setq newstr (getstring T "\nEnter new string "))

These two strings are saved as oldstr and newstr. Note that the T argument is used with getstring to allow the user to use spaces in the string.

The next set of expressions do the work of the program. First, The number of characters of the string to be replaced, oldstr, is found by using the strlen function:

(setq osleng (strlen oldstr))

This value is stored with a variable called osleng. Osleng will be used to find exactly where in the line of text the old string occurs in the line of text being edited (see figure 7.2).

Figure 7.2: Using the strlen function

The following while function uses osleng\ to find the exact location of oldstr within oldtxt.

(while (and (/= oldstr oldt)(<= count otleng))

(setq count (1+ count))

(setq oldt (substr oldtxt count osleng))

);end WHILE

The while expression tests for two conditions. The first test is to see of the current string being read matches the string entered at the "String to be changed" prompt. The second test checks to see if the end of the text line has been reached. The and logical operator is used to make sure that both test conditions are met before it continues evaluating its other expressions.

We see a new function substr in this group of expressions:

(Setq oldt (substr oldtxt count osleng))

Substr extracts a sequence of characters from a string. Its syntax is:

(substr

[string or string variable]

[beginning of substring][end of substring]

)

The first argument to substr is the string within which a substring is to be extracted. By substring, we mean a group of characters that are contained within the main string. The substring can be any contiguous sequence of characters within the main string including the entire string itself. The second argument is the beginning location for the substring. This can be an integer from 1 to the total number of characters in the main string. The third argument is the ending location of the substring. This value is an integer greater than or equal to the value for the beginning of the substring and it determines the ending location of the substring (see figure 7.3).

Figure 7.3: Using the substr function

The while expression extracts a group of characters from oldtxt starting at the beginning. It stores this substring in the variable oldt. Oldt is then compared with oldstr to see if they match. If the don't match, then while advances to the next group of characters in oldtxt and compares this new group to oldstr. This goes on until a match is found or the end of oldtxt is reached (See figure 7.4).

Figure 7.4: Using the while expression to find a matching string.

 

String data types are case sensitive, This means that if you had entered "BATTLE" instead of "battle" at the string to change prompt, you would have gotten the message:

No matching string found.

The string "BATTLE" is not equal to "battle" so as edtxt tries to find a string that matches "BATTLE", it never finds it.

When the while expression is done, the next group of expressions takes the old text line apart and replaces the old string with the new. First the if function is used to test whether the oldstring was indeed found.

(if (<= count otleng)

The if expression checks to see if the variable count is equal to or less than the length of the old text line. If count is less than otleng, then the following set of expressions are evaluated:

(progn

(setq old1 (substr oldtxt 1 (1- count)))

(setq old2 (substr oldtxt (+ count osleng) otleng))

(setq newtxt (strcat old1 newstr old2))

(revtxt)

)

The progn function allows the group of expressions that follow to appear as one expression to the if function. The first expression of this group:

(setq old1 (substr oldtxt 1 (1- count)))

separates out the first part of the old text line just before the old string. This is done using the substr function and the count variable to find the beginning of the old string (see figure 7.5).

Figure 7.5: Finding the string before oldstr

The next expression:

(setq old2 (substr oldtxt (+ count osleng) otleng))

separates out the last part of the old text line starting just after the old string. Again this is done using the substr function and the count variable. This time, count is added to osleng to find the location of the end of the old string. Otleng is used for the substring length. Even though its value is greater than the length of the substring w wan, AutoLISP will read the substring to the end of Oldtxt (see figure 7.6).

Figure 7.6: Finding the string after oldstr

 

Finally, the expression:

(setq newtxt (strcat old1 newstr old2))

combines the first and last part of the old text line with the new string to form the replacement text line (see figure 7.7).

Figure 7.7: Combining the old string with the new

 

The last expression in this group:

(revtxt)

is a user defined function that does the work of replacing the old text with the new.

(defun revtxt ()

(setq newtxt (cons 1 newtxt))

(entmod (subst newtxt txtstr oldobj))

In the event that count is greater than otleng, the following expression is evaluated:

(princ "\nNo matching string found.")

);end IF

This expression prints the message:

No matching string found.

to the prompt line.

The very last expression of the program:

(PRINC)

);END C:EDTXT

seems pretty useless at first glance. Princ without any arguments prints a blank to the prompt line. If this expression were not here, however, AutoLISP would display the value of the last expression evaluated. Remember that AutoLISP constantly cycles through the read-evaluate-print loop. The generally, the value of the last expression evaluated is printed to the prompt line. While this doesn't affect the workings of the program, it may prove to be an annoyance to the user or it may confuse someone not familiar with the program. Since princ will print a blank at the prompt line when no arguments are supplied, it is often used without arguments at the end of a program simply to keep the appearance of the program clean. If you like, try deleting the Princ expression from the program and reload and run the program again. You will a value will appear in the prompt line when C:EDTXT finishes running.

How to Convert Numbers to String and Back

There are times when it is necessary to convert a string value to a number or vice versa. Suppose, for example, that you want to be able to control the spacing of numbers generated by the program in chapter 5. You may recall that this program creates a sequence of numbers equally spaced. The user is able to determine the beginning and ending numbers and the location of the beginning number but cannot determine the distance between numbers. You can use the rtos function to help obtain a distance value and include it with the program. Figure 7.8 shows the C:SEQ program from chapter 5 modified to accept distance input.

 


(defun C:SEQ (/ pt1 currnt last)
(setq pt1    (getpoint "\nPick start point: "))
(setq spc    (getdist pt1 "\nEnter number spacing: "))
(setq currnt (getint "\nEnter first number: "))
(setq last   (getint "\nEnter last number: "))
(setq stspc  (rtos spc 2 2))
(setq stspc  (strcat "@" stspc "<0" ))
(command "text" pt1 "" "" currnt)
  (repeat (- last currnt)
    (setq currnt (1+ currnt))
    (command "text" stspc "" "" currnt)
  )
)

 


Figure 7.8: The sequential number program
 

Converting a Number to a String

Exit AutoCAD and open the AutoLISP file seq.lsp. Make the changes shown in bold face type in figure 7.10. Save and exit the seq.lsp file and return to the file chapt7. Load the C:SEQ program and do the following:

1. Enter seq at the command prompt.

2. At the prompt:

Pick start point:

pick a point at coordinate 1,3.

3. At the prompt:

Enter spacing:

enter .5.

4. At the prompt:

Enter first number:

enter 4.

5. At the last prompt:

Enter last number:

enter 12.

The numbers 4 through 12 will appear beginning at your selected start point and spaced at 0.5 unit intervals.

The program starts by prompting the user to pick a starting point:

(defun C:SEQ (/ pt1 pt2 currnt last)

(setq pt1 (getpoint "\nPick start point: "))

A new prompt is added that obtains the spacing for the numbers:

(setq spc (getdist pt2 "\nEnter number spacing: "))

The spacing is saved as the symbol spc. The program continues by prompting the user to enter starting and ending value:

(setq currnt (getint "\nEnter first number: "))

(setq last (getint "\nEnter last number: "))

Next, the function rtos is used to convert the value of spc to a string:

(setq stspc (rtos spc 2 2))

the syntax for rtos is:

(rtos [real or integer value][unit style code][precision])

The first argument to rtos is the number being converted. It can be a real or integer. The next argument is the unit style code. Table shows a listing of these codes and their meaning.

Code

Format

1

Scientific

2

Decimal

3

Feet and decimal inches

4

Feet and inches

5

Fractional units

This code determines the style the number will be converted to. For example, if you want a number to be converted to feet and inches, you would use the code 4. The third argument, precision, determines to how many decimal places to convert. In our example, we use the code 2 for unit style and 2 for the number of decimal places to convert to a string.

The next expression combines the converted number with the strings "@" and "<0" to form a string that can be used in with the command function:

(setq stspc (strcat "@" stspc "<0" ))

The next two expressions set up the location of the beginning of the text:

(command "text" pt1 "" "" currnt)

This is done because in the next set of expressions, The string that locates the text, "@distance<0", gives a distance and direction rather than a point. The previous expressions locate a point which will cause the Text command in the next expression to place the text in the proper place:

(repeat (- last currnt)

(setq currnt (1+ currnt))

(command "text" stspc "" "" currnt)

)

)

In the last three expressions, the repeat function is used to issue the text command, enter the number and advance to the next number repeatedly until the last number is in place (see figure 7.9).

Figure 7.9: Writing the numbers into the AutoCAD file

 

Converting Other Data Types

Before we continue, we should briefly look at several other functions that offer data type conversion. These functions are listed in table .

Function

Uses

angtos

Converts real numbers (radians) into string values.

ascii

Converts a string into its ASCII character code.

atoi

Converts a string a string into an integer.

 itoa

Converts an integer to a string.

chr

Converts an integer representing an ASCII character code into a string.

 

Angtos works in a similar way to rtos. It accepts a unit style code and a precision value. Its syntax is:

(angtos [angle value][unit style code][precision])

All of the other functions listed in table take a single item, the value to be converted, as their argument. For example, to convert an integer into a string, you could use the following expression:

(itoa 55)

The resulting value is "55".

The functions ascii and chr convert ASCII character codes. These are numeric values that represent letters, numbers and symbols. Figure 7.10 shows these codes and their meaning.

Code

Meaning

Code

Meaning

Code

Meaning

Code

Meaning

Code

Meaning

Code

Meaning

07

Beep

46

.

65

A

84

T

103

g

122

z

09

Tab

47

/

66

B

85

U

104

h

123

{

10

New line

48

0

67

C

86

V

105

i

124

|

13

Return

49

1

68

D

87

W

106

j

125

}

27

Escape

50

2

69

E

88

X

107

k

126

~

32

Space

51

3

70

F

89

Y

108

l

33

!

52

4

71

G

90

Z

109

m

34

"

53

5

72

H

91

[

110

n

35

#

54

6

73

I

92

\

111

o

36

$

55

7

74

J

93

]

112

p

37

%

56

8

75

K

94

^

113

q

38

&

57

9

76

L

95

_

114

r

39

'

58

:

77

M

96

`

115

s

40

(

59

;

78

N

97

a

116

t

41

)

60

<

79

O

98

b

117

u

42

*

61

=

80

P

99

c

118

v

43

+

62

>

81

Q

100

d

119

w

44

,

63

?

82

R

101

e

120

x

45

-

64

@

83

S

102

f

121

y

Figure 7.10: The ASCII character codes 

 

How to read ASCII text files

There are many reasons why you may want to have a program read from and write to an ASCII file. You may store commonly used general notes in ASCII files on your hard disk which you would import into your drawing. Or you may want to store drawing information on disk for later retrieval such as layering setup or block lists.

 

Using a File Import Program

The program shown in figure 7.11 is a rudimentary text import program. In this section, you will use it to examine the way AutoLISP reads external ASCII files.

 


(Defun C:IMPRT (/ sp dt stl qst)
(setq nme (getstring "\nName of text file to import: "))
(setq sp  (getpoint "\nText starting point: "))
(setq txt (open nme "r"))
(setq dt  (read-line txt))
(setq lns (getdist "\nEnter line spacing in drawing units: "))
(setq ls  (rtos lns 2 2))
(setq ls  (strcat "@" ls "<-90"))
(command "text" sp "" "" dt)
   (while (/= dt nil)
      (setq dt (read-line txt))
      (command "text" ls "" "" dt)
   )
(close txt)
(command "redraw")
)

Figure 7.11: A text import program

 

Create an ASCII file containing the program in figure 7.13. Give it the name Imprt.lsp. Go back to the Chapt7 AutoCAD file and load the Imprt.lsp file. Now run the program:

1. Enter imprt at the Command prompt.

2. At the prompt:

Name of text file to import:

Enter imprt.lsp.

3. At the next prompt:

Text starting point:

pick a point at coordinate 2,8.

4. At the next prompt:

Enter line spacing in drawing units:

enter .4.

The contents of the file Imprt.lsp will be written into the drawing area using AutoCAD text.

The C:IMPRT program starts out by prompting the user to identify the file to be imported. The user is prompted to enter the name of the file to be imported:

(Defun C:IMPRT (/ sp dt stl qst)

(setq nme (getstring "\nName of text file to import: "))

The entered name is saved as the variable nme. Next, the starting point is gotten:

(setq sp (getpoint "\nText starting point: "))

This point is saved as sp. The last prompt sets up the line spacing:

(setq lns (getdist sp "\nEnter line spacing in drawing units: "))

The spacing distance is assigned to the variable lns. Note that getdist is used so the user can input a distance either through the keyboard or cursor.

In the next line, the AutoLISP function open is used to open the file to be imported:

(setq txt (open nme "r"))

In this expression, you are telling AutoLISP to open a file to be read, then assign that file to the variable txt. From this point on, you can treat the variable txt as if it were a read only version of the file itself. This variable that assumes the idobject of the file is called the file descriptor. At first, it may seem confusing that you assign the file name to a variable that is used to locate and open the file then assign the open file to a variable of a different name. But you cannot perform file reads and writes directly through a variable of the same name as the file. You can, however, assign an open file to a symbol then treat that symbol as if it were the file itself.

The syntax for open is:

(open [name of file] [read or write code])

The first argument is the name of the file to be opened. The second argument is a code that tells AutoLISP whether to allow read only, write only or appending operations on the file. The following table shows the codes and their meaning.

Code

Uses

"r"

Open a file for reading only. If the file does not exist, any attempts to read from it will result in an error message.

"w"

Open a file to write to. If the file already exists, its contents will be written over. If the file does not exist, it will be created

"a"

Open a file and append to the end if it. If the file does not exist, it will be created.

The next line uses the AutoLISP function read-line to read the first line of text from the open file:

(setq dt (read-line txt))

A line of text is read from the file represented by the symbol txt and is assigned to the variable dt. Read-line has only one argument, the file descriptor. When the file is first opened, AutoLISP goes to the beginning of the file in preparation to read it. Read-line reads the first line then AutoLISP moves to the second line waiting for further instructions to read the file. The next time the expression:

(read-line txt)

is evaluated, AutoLISP will read the next line after the previously red line then move to the following line and wait for another read-line function call.

The next two lines set up the location of the beginning of the text in the drawing editor:

(setq ls (rtos lns 2 2))

(setq ls (strcat "@" ls "<-90"))

The numeric value entered at the line spacing prompt is converted to a string then appended to the "@" and "<-90" strings to create a string that can be used in the text command that follows. The next line writes the text from the first line of the file into the AutoCAD drawing:

(command "text" sp "" "" dt)

The following while expression continually reads lines from the open file and writes them to the AutoCAD drawing editor:

(while (/= dt nil)

(setq dt (read-line txt))

(command "text" ls "" "" dt)

)

The read-line function will return nil when it reaches the end of the file. At that point, the while expression stops its recursion).

Finally, to take care of housekeeping, the open file is closed.

(close txt)

This is a very important step in the file reading process. If a file is not closed, the contents of that file can be lost.

We should mention that C:IMPRT requires the current text style to have a height value of 0. If this is not the case, then the program will not work properly. This is because in the line that actually writes the text into the drawing editor:

(command "text" ls "" "" dt)

assumes that AutoCAD will prompt for a height value for the text. The height prompt occurs only when the current text style has a height value of 0. If the current text style has a height value other than 0, the height prompt is skipped. This would cause the above expression to add one too many returns in the text command sequence (see figure 7.12).

Figure 7.12: The text command expects specific input

Writing ASCII Files to Disk

AutoLISP lets you create ASCII files. You can use this capability to store different types of information ranging from the current drawing status to general notes that appear in a drawing. The program in figure 7.13 demonstrates this capability.

 


;Program to export text from AutoCAD -- Exprt.lsp
(Defun C:EXPRT (/ fname txt selset count nme oldtx)
  (setq fname (getstring "\nEnter name of file to be saved: "))
     (setq txt (open fname "w"))                     ;open file, assign symbol
     (setq selset (ssget))                           ;get selection set
     (setq count 0)                                  ;set count to zero
     (if (/= selset nil)
         (while (< count (sslength selset))          ;while count < # of lines
                (setq nme (ssname selset count))     ;extract text string
                (setq oldtx (cdr (assoc 1 (entget nme))))
                (write-line oldtx txt)               ;write string to file
                (setq count (1+ count))              ;go to next line
         );end while
     );end if
(close txt)                                          ;close file
);end C:EXPRT

 


Figure 7.13: A text export program
 

Using a Text Export Program

Exit AutoCAD then create a file called Exprt.lsp containing the program shown in figure 7.16. Return to AutoCAD, load the file and proceed with the following:

1. Erase the text you imported previously.

2. Use the dtext command and starting the text at the coordinate 2,8, write the following lines:

For want of a nail, the shoe was lost;

For want of a shoe, the horse was lost;

For want of a horse, the rider was lost;

3. Enter exprt to start the text export program.

4. At the prompt:

Enter name of file to save:

Enter test.txt.

5. At the prompt:

Select objects:

Pick the lines of text you just entered picking each one individually from top to bottom. Press return when you are done.

The file test.txt is created containing the text you had just entered using AutoCAD's Dtext command. To make sure the file exists, enter the following at the command prompt:

type test.txt

The AutoCAD type command is the same as the DOS type command. It displays the contents of a text file. AutoCAD will switch to text mode and the contents of test.txt will be displayed on the screen.

The Exprt program starts by prompting the user to enter a name for the file to be saved to:

(Defun c:exprt (/ ts n dir)

(setq fname (getstring "\nEnter name of file to save: "))

Then, just as with the imprt program, the open function opens the file:

(setq txt (open n "w"))

In this case, the "w" code is used with the open functions since this file is to be written to. The next line obtains a group of objects for editing using the ssget function:

(setq selset (ssget))

This selection set is saved as the variable selset. Next, a variable count is give the value 0 in preparation for the while expression that follows:

(setq count 0)

The next if expression checks to see that the user has indeed picks objects for editing.

(if (/= selset nil)

If the variable selset does not return nil, then the while expression is evaluated:

(while (< count (sslength selset))

(setq entnme (ssname selset count))

(setq oldtx (cdr (assoc 1 (entget entnme))))

(write-line oldtx txt)

(setq count (1+ count))

)

This while expression uses the count variable to determine the number of times it must evaluate its set of expressions:

(while (< count (sslength selset))

The sslength function returns the number of objects contained in a selection set. In this case, it returns the number of objects recorded in the variable selset. This value is compared with the variable count to determine whether or not to evaluate the expressions found under the while expression.

The next two expressions extract the text string value from the first of the objects selected:

(setq entnme (ssname selset count))

(setq oldtx (cdr (assoc 1 (entget entnme))))

This extraction process involves several new functions which are discussed in chapter . For now, just accept that the end result is the assignment of the text value of the selected object to the variable oldtx.

Now the actual writing to the file occurs:

(write-line oldtx txt)

Here the write-line functions reads the string held by oldtx and writes it to the file represented by the variable txt.

Write-line's syntax is:

(write-line [string][file descriptor])

The first argument is the string to be written to file while the second argument is a variable assigned to the open file.

The next line increases the value of count by one:

(setq count (1+ count))

This expression counts the number of times a string of text, and therefore an object, has been processed. Since the while test expression checks to see if the value of count is less than the number of objects selected, once count reaches a value equivalent to the number of objects selected and processed, the while expression stops processing.

Finally, the all important close expression appears:

)

(close txt)

)

Just as with the C:IMPRT program, close must be used to properly close the file under DOS, otherwise its contents may be in-accessible.

Read-line and write-line are two of several file read and write functions available in AutoLISP. Table shows several other functions along with a brief description.

Function

Description

(prin1 symbol/expression)

Prints any expression to the screen prompt. If a file descriptor is included as an argument, the expression is written to the file as well.

(princ symbol/expression)

The same as prin1 but execute's control characters. Also, String quotation marks are dropped.

print symbol/expression)

The Same as prin1 but a new line is printed before its expression and a space is printed after.

(read-char file_descriptor)

Reads a single character from the keyboard. If a file descriptor is included as an argument, it reads a character from the file. The value returned is in the form of an ASCII character code.

read-line file_descriptor)

Reads a string from the keyboard or a line of text from an open file.

write-char integer file_descriptor)

Writes a single character to the screen prompt or if a file descriptor is provided, to an open file. The character argument is a number representing an ASCII character code.

write-line string file_descriptor)

Writes a string to the screen prompt or if a file descriptor is provided, to an open file.

The three functions prin1, princ, and print are nearly identical with some slight differences. All three use the same syntax as shown in the following:

(princ [string or string variable][optional file descriptor])

The file descriptor is a symbol that has been assigned an open file.

The main difference between these three functions is in what they produce as values. The following shows an expression using prin1 followed by the resulting value:

(prin1 "\nFor want of a nail...")

"For want of a nail...""\nFor want of a nail..."

Notice that the string argument to prin1 is printed twice to the prompt line. This is because both prin1 and AutoLISP will print something to the prompt. Prin1 prints its a literal version of its string argument. AutoLISPs read-evaluate-print loop also prints the value of the last object evaluated. The net result it the appearance of the string twice on the same line.

Princ differs from prin1 in that instead of printing a literal version of its string argument, it will act on any control characters included in the string:

(princ "\nFor want of a nail...")

For want of a nail..."\nFor want of a nail..."

In the prin1 example, the \n control character is printed without acting on it. In the princ example above, the \n character causes the AutoCAD prompt to advance one line. Also, the string is printed without the quotation marks. Again, the AutoLISP interpreter prints the value of the string directly to the prompt line after princ does it's work. Table Shows the other control characters and what they do.

Character

Use

\e

Escape

\n

New line

\r

Return

\t

Tab

\nnn

Character whose octal code is nnn

The print function differs from the prin1 function in that it advances the prompt one line before printing the string then it adds a space at the end of the string:

(print "\nFor want of a nail...")

"\nFor want of a nail..." "\nFor want of a nail..."

Just as with prin1, print prints a literal version of its string argument.

Conclusion

While a good deal of your effort using AutoLISP will concentrate on graphics and numeric computation, the ability to manipulate string data will be an important part of your work. You have been introduced to those functions that enable you to work with strings.

You have also seen how these functions work together to perform some simple tasks like reading and writing text files. But you don't have to limit yourself to using these functions for text editing. Since any kind of information can be stored as a string, you may find ways to further enhance your use of AutoCAD through the manipulation of string data. One of the more obvious uses that comes to mind is the importation of numeric data for graphing, charting or other types of data analysis. As long as data is stored in an ASCII format, AutoLISP can read it. And with AutoLISP's data conversion functions, numeric data can be easily translated from ASCII files.