From 4b42bf9358eca2c4597837e87dd10e49c1b60bc7 Mon Sep 17 00:00:00 2001
From: Hans Bolinder This module provides an interface to standard Erlang IO servers.
+ This module provides an interface to standard Erlang I/O servers.
The output functions all return In the following description, all functions have an optional
@@ -45,10 +45,9 @@
marker="#put_chars/2">put_chars function should be in the
If an io_device() is set in binary mode, the functions Either An IO device. Either
Retrieves the number of columns of the
Writes the characters of
Writes the characters of
The input characters. If the device supports Unicode, +
The input characters. If the IO device supports Unicode, the data may represent codepoints larger than 255 (the - latin1 range). If the io_server() is set to deliver + latin1 range). If the I/O server is set to deliver binaries, they will be encoded in UTF-8 (regardless of if - the device actually supports Unicode or not).
+ the IO device actually supports Unicode or not).The characters in the line terminated by a LF (or end of - file). If the device supports Unicode, + file). If the IO device supports Unicode, the data may represent codepoints larger than 255 (the - latin1 range). If the io_server() is set to deliver + latin1 range). If the I/O server is set to deliver binaries, they will be encoded in UTF-8 (regardless of if - the device actually supports Unicode or not).
+ the IO device actually supports Unicode or not).This function requests all available options and their current values for a specific io_device(). Example:
+This function requests all available options and their current values for a specific IO device. Example:
1> {ok,F} = file:open("/dev/null",[read]). {ok,<0.42.0>} @@ -217,19 +216,19 @@Set options - Set options for the io_device() (
+). IoDevice Set options for the standard IO device (
). IoDevice Possible options and values vary depending on the actual - io_device(). For a list of supported options and their current values - on a specific device, use the
-getopts/1 function.The options and values supported by the current OTP io_devices are:
+The options and values supported by the current OTP IO devices are:
binary, list or {binary, boolean()} - -
If set in binary mode (binary or {binary,true}), the io_server() sends binary data (encoded in UTF-8) as answers to the get_line, get_chars and, if possible, get_until requests (see the I/O protocol description in STDLIB User's Guide for details). The immediate effect is that
-get_chars/2,3 andget_line/1,2 return UTF-8 binaries instead of lists of chars for the affected device.By default, all io_devices in OTP are set in list mode, but the io functions can handle any of these modes and so should other, user written, modules behaving as clients to I/O-servers.
+If set in binary mode (binary or {binary,true}), the I/O server sends binary data (encoded in UTF-8) as answers to the get_line, get_chars and, if possible, get_until requests (see the I/O protocol description in STDLIB User's Guide for details). The immediate effect is that
+get_chars/2,3 andget_line/1,2 return UTF-8 binaries instead of lists of chars for the affected IO device.By default, all IO devices in OTP are set in list mode, but the io functions can handle any of these modes and so should other, user written, modules behaving as clients to I/O-servers.
This option is supported by the standard shell (group.erl), the 'oldshell' (user.erl) and the file I/O servers.
@@ -261,10 +260,10 @@ {echo, boolean()}
Specifies how characters are input or output from or to the actual device, implying that i.e. a terminal is set to handle Unicode input and output or a file is set to handle UTF-8 data encoding.
-The option does not affect how data is returned from the io-functions or how it is sent in the I/O-protocol, it only affects how the io_device() is to handle Unicode characters towards the "physical" device.
-The standard shell will be set for either unicode or latin1 encoding when the system is started. The actual encoding is set with the help of the "LANG" or "LC_CTYPE" environment variables on Unix-like system or by other means on other systems. The bottom line is that the user can input Unicode characters and the device will be in {encoding, unicode} mode if the device supports it. The mode can be changed, if the assumption of the runtime system is wrong, by setting this option.
-The io_device() used when Erlang is started with the "-oldshell" or "-noshell" flags is by default set to latin1 encoding, meaning that any characters beyond codepoint 255 will be escaped and that input is expected to be plain 8-bit ISO-latin-1. If the encoding is changed to Unicode, input and output from the standard file descriptors will be in UTF-8 (regardless of operating system).
+Specifies how characters are input or output from or to the actual IO device, implying that i.e. a terminal is set to handle Unicode input and output or a file is set to handle UTF-8 data encoding.
+The option does not affect how data is returned from the io-functions or how it is sent in the I/O-protocol, it only affects how the IO device is to handle Unicode characters towards the "physical" device.
+The standard shell will be set for either unicode or latin1 encoding when the system is started. The actual encoding is set with the help of the "LANG" or "LC_CTYPE" environment variables on Unix-like system or by other means on other systems. The bottom line is that the user can input Unicode characters and the IO device will be in {encoding, unicode} mode if the IO device supports it. The mode can be changed, if the assumption of the runtime system is wrong, by setting this option.
+The IO device used when Erlang is started with the "-oldshell" or "-noshell" flags is by default set to latin1 encoding, meaning that any characters beyond codepoint 255 will be escaped and that input is expected to be plain 8-bit ISO-latin-1. If the encoding is changed to Unicode, input and output from the standard file descriptors will be in UTF-8 (regardless of operating system).
Files can also be set in {encoding, unicode}, meaning that data is written and read as UTF-8. More encodings are possible for files, see below.
{encoding, unicode | latin1} is supported by both the standard shell (group.erl including werl on windows), the 'oldshell' (user.erl) and the file I/O servers.
The following control sequences are available:
@@ -400,9 +399,9 @@ ok 2> io:fwrite("|~10.5c|~-10.5c|~5c|~n", [$a, $b, $c]). | aaaaa|bbbbb |ccccc| ok -If the Unicode translation modifier ('t') is in effect, +
If the Unicode translation modifier (
1> io:fwrite("~tc~n",[1024]). @@ -442,7 +441,7 @@ ok
Prints the argument with the
Like
16> io:fwrite("~.10#~n", [31]). 10#31 @@ -651,7 +650,7 @@ ok {shell,eval_loop,3}]} in function io:o_request/2
In this example, an attempt was made to output the single - character '65' with the aid of the string formatting directive + character 65 with the aid of the string formatting directive "~s".
@@ -682,7 +681,7 @@ ok return suppression character. It provides a method to specify a field which is to be omitted.An optional sign character is expected. A sign
- character '-' gives the return value
Retrieves the number of rows of the
In certain situations, especially when the standard output is redirected, access to an io_server() specific for error messages might be convenient. The io_device 'standard_error' can be used to direct output to whatever the current operating system considers a suitable device for error output. Example on a Unix-like operating system:
+In certain situations, especially when the standard output is redirected, access to an I/O-server specific for error messages might be convenient. The IO device
$ erl -noshell -noinput -eval 'io:format(standard_error,"Error: ~s~n",["error 11"]),'\ 'init:stop().' > /dev/null diff --git a/lib/stdlib/doc/src/io_protocol.xml b/lib/stdlib/doc/src/io_protocol.xml index 0ff3d5c1ee..d36bf2042f 100644 --- a/lib/stdlib/doc/src/io_protocol.xml +++ b/lib/stdlib/doc/src/io_protocol.xml @@ -5,7 +5,7 @@1999 -2011 +2012 Ericsson AB. All Rights Reserved. @@ -35,10 +35,10 @@ The I/O-protocol in Erlang specifies a way for a client to communicate -with an io_server and vice versa. The io_server is a process handling the -requests and that performs the requested task on i.e. a device. The +with an I/O server and vice versa. The I/O server is a process that handles +the requests and performs the requested task on e.g. an IO device. The client is any Erlang process wishing to read or write data from/to the -device.
+IO device.The common I/O-protocol has been present in OTP since the beginning, but has been fairly undocumented and has also somewhat @@ -53,85 +53,85 @@ implement than the original. It can certainly be argumented that the current protocol is too complex, but this text describes how it looks today, not how it should have looked.
-The basic ideas from the original protocol still hold. The io_server +
The basic ideas from the original protocol still hold. The I/O server and client communicate with one single, rather simplistic protocol and -no server state is ever present in the client. Any io_server can be +no server state is ever present in the client. Any I/O server can be used together with any client code and client code need not be aware -of the actual device the io_server communicates with.
+of the actual IO device the I/O server communicates with.- Protocol basics +Protocol Basics -As described in Robert's paper, servers and clients communicate using -io_request/io_reply tuples as follows:
+As described in Robert's paper, I/O servers and clients communicate using +
io_request /io_reply tuples as follows:{io_request, From, ReplyAs, Request}
-
{io_reply, ReplyAs, Reply}The client sends an io_request to the io_server and the server -eventually sends a corresponding reply.
+The client sends an
io_request tuple to the I/O server and +the server eventually sends a correspondingio_reply tuple.-
-- From is the pid() of the client, the process which the io_server -sends the reply to.
- -- ReplyAs can be any datum and is simply returned in the corresponding -io_reply. The io-module in the Erlang standard library simply uses the pid() -of the io_server as the ReplyAs datum, but a more complicated client -could have several outstanding io-requests to the same server and -would then use i.e. a reference() or something else to differentiate among -the incoming io_reply's. The ReplyAs element should be considered -opaque by the io_server. Note that the pid() of the server is not -explicitly present in the io_reply. The reply can be sent from any -process, not necessarily the actual io_server. The ReplyAs element is -the only thing that connects one io_request with an io_reply.
- -- Request and Reply are described below.
+- + +
From is thepid() of the client, the process which +the I/O server sends the IO reply to.- + +
ReplyAs can be any datum and is returned in the corresponding +io_reply . Theio module simply uses the pid() +of the I/O server as theReplyAs datum, but a more complicated client +could have several outstanding I/O requests to the same I/O server and +would then use i.e. areference() or something else to differentiate among +the incoming IO replies. TheReplyAs element should be considered +opaque by the I/O server. Note that thepid() of the I/O server is not +explicitly present in theio_reply tuple. The reply can be sent from any +process, not necessarily the actual I/O server. TheReplyAs element is +the only thing that connects one I/O request with an I/O-reply.Request andReply are described below.When an io_server receives an io_request, it acts upon the actual -Request part and eventually sends an io_reply with the corresponding -Reply part.
+When an I/O server receives an
io_request tuple, it acts upon the actual +Request part and eventually sends anio_reply tuple with the corresponding +Reply part.- Output requests +Output Requests -To output characters on a device, the following Requests exist:
+To output characters on an IO device, the following
Request s exist:{put_chars, Encoding, Characters}
{put_chars, Encoding, Module, Function, Args}-
-- Encoding is either 'unicode' or 'latin1', meaning that the +
- - -
Encoding is eitherunicode orlatin1 , meaning that the characters are (in case of binaries) encoded as either UTF-8 or - iso-latin-1 (pure bytes). A well behaved io_server should also - return error if list elements contain integers > 255 when the - Encoding is set to latin1. Note that this does not in any way tell - how characters should be put on the actual device or how the - io_server should handle them. Different io_servers may handle the - characters however they want, this simply tells the io_server which - format the data is expected to have. In the Module/Function/argument - case, the Encoding tells which format the designated function - produces. Note that byte-oriented data is simplest sent using latin1 - Encoding- Characters are the data to be put on the device. If Encoding is - latin1, this is an iolist(). If Encoding is unicode, this is an - Erlang standard mixed unicode list (one integer in a list per + ISO-latin-1 (pure bytes). A well behaved I/O server should also + return error if list elements contain integers > 255 when +
+ +Encoding is set tolatin1 . Note that this does not in any way tell + how characters should be put on the actual IO device or how the + I/O server should handle them. Different I/O servers may handle the + characters however they want, this simply tells the I/O server which + format the data is expected to have. In theModule /Function /Args + case,Encoding tells which format the designated function + produces. Note that byte-oriented data is simplest sent using the ISO-latin-1 + encoding.- Characters are the data to be put on the IO device. If
-Encoding is +latin1 , this is aniolist() . IfEncoding isunicode , this is an + Erlang standard mixed Unicode list (one integer in a list per character, characters in binaries represented as UTF-8).- Module, Function, Args denotes a function which will be called to - produce the data (like io_lib:format). Args is a list of arguments +
Module ,Function , andArgs denote a function which will be called to + produce the data (likeio_lib:format/2 ).Args is a list of arguments to the function. The function should produce data in the given - Encoding. The io_server should call the function as apply(Mod, Func, - Args) and will put the returned data on the device as if it was sent - in a {put_chars, Encoding, Characters} request. If the function +Encoding . The I/O server should call the function as +apply(Mod, Func, Args) and will put the returned data on the IO device as if it was sent + in a{put_chars, Encoding, Characters} request. If the function returns anything else than a binary or list or throws an exception, an error should be sent back to the client.The server replies to the client with an io_reply where the Reply +
The I/O server replies to the client with an
io_reply tuple where theReply element is one of:ok
@@ -139,49 +139,50 @@ element is one of:-
-- Error describes the error to the client, which may do whatever it - wants with it. The Erlang io-module typically returns it as is.
+Error describes the error to the client, which may do whatever + it wants with it. The Erlangio + module typically returns it as is.For backward compatibility the following Requests should also be -handled by an io_server (these messages should not be present after +
For backward compatibility the following
Request s should also be +handled by an I/O server (these requests should not be present after R15B of OTP):{put_chars, Characters}
-
{put_chars, Module, Function, Args}These should behave as {put_chars, latin1, Characters} and {put_chars, -latin1, Module, Function, Args} respectively.
+These should behave as
{put_chars, latin1, Characters} and +{put_chars, latin1, Module, Function, Args} respectively.Input Requests -To read characters from a device, the following Requests exist:
+To read characters from an IO device, the following
Request s exist:{get_until, Encoding, Prompt, Module, Function, ExtraArgs}
-
-- Encoding denotes how data is to be sent back to the client and +
-- + binaries, but the list may contain numbers > 255 if the
Encoding denotes how data is to be sent back to the client and what data is sent to the function denoted by - Module/Function/ExtraArgs. If the function supplied returns data as a +Module /Function /ExtraArgs . If the function supplied returns data as a list, the data is converted to this encoding. If however the function supplied returns data in some other format, no conversion - can be done and it's up to the client supplied function to return - data in a proper way. If Encoding is latin1, lists of integers + can be done and it is up to the client supplied function to return + data in a proper way. IfEncoding islatin1 , lists of integers 0..255 or binaries containing plain bytes are sent back to the - client when possible, if Encoding is unicode, lists with integers in - the whole unicode range or binaries encoded in UTF-8 are sent to the + client when possible; ifEncoding isunicode , lists with integers in + the whole Unicode range or binaries encoded in UTF-8 are sent to the client. The user supplied function will always see lists of integers, never - binaries, but the list may contain numbers > 255 if the Encoding is - 'unicode'.Encoding is +unicode .- Prompt is a list of characters (not mixed, no binaries) or an atom() - to be output as a prompt for input on the device. The Prompt is - often ignored by the io_server and a Prompt set to '' should always - be ignored (and result in nothing being written to the device).
+- -
Prompt is a list of characters (not mixed, no binaries) or an atom + to be output as a prompt for input on the IO device.Prompt is + often ignored by the I/O server and if set to'' it should always + be ignored (and result in nothing being written to the IO device).Module, Function, ExtraArgs denotes a function and arguments to +
{done, Result, RestChars}@@ -189,23 +190,23 @@ latin1, Module, Function, Args} respectively.
Module ,Function , andExtraArgs denote a function and arguments to determine when enough data is written. The function should take two additional arguments, the last state, and a list of characters. The function should return one of:
{more, Continuation} -The Result can be any Erlang term, but if it is a list(), the - io_server may convert it to a binary() of appropriate format before - returning it to the client, if the server is set in binary mode (see +
The
-Result can be any Erlang term, but if it is alist() , the + I/O server may convert it to abinary() of appropriate format before + returning it to the client, if the I/O server is set in binary mode (see below).The function will be called with the data the io_server finds on - its device, returning {done, Result, RestChars} when enough data is - read (in which case Result is sent to the client and RestChars are - kept in the io_server as a buffer for subsequent input) or {more, - Continuation}, indicating that more characters are needed to - complete the request. The Continuation will be sent as the state in +
The function will be called with the data the I/O server finds on + its IO device, returning
{done, Result, RestChars} when enough data is + read (in which caseResult is sent to the client andRestChars is + kept in the I/O server as a buffer for subsequent input) or +{more, Continuation} , indicating that more characters are needed to + complete the request. TheContinuation will be sent as the state in subsequent calls to the function when more characters are available. When no more characters are available, the function - shall return {done,eof,Rest}. + shall return{done, eof, Rest} . The initial state is the empty list and the data when an - end of file is reached on the device is the atom 'eof'. An emulation - of the get_line request could be (inefficiently) implemented using + end of file is reached on the IO device is the atomeof . An emulation + of theget_line request could be (inefficiently) implemented using the following functions:-module(demo). @@ -214,7 +215,9 @@ latin1, Module, Function, Args} respectively. until_newline(_ThisFar,eof,_MyStopCharacter) -> {done,eof,[]}; until_newline(ThisFar,CharList,MyStopCharacter) -> - case lists:splitwith(fun(X) -> X =/= MyStopCharacter end, CharList) of + case + lists:splitwith(fun(X) -> X =/= MyStopCharacter end, CharList) + of {L,[]} -> {more,ThisFar++L}; {L2,[MyStopCharacter|Rest]} -> @@ -222,45 +225,47 @@ until_newline(ThisFar,CharList,MyStopCharacter) -> end. get_line(IoServer) -> - IoServer ! {io_request, self(), IoServer, {get_until, unicode, '', - ?MODULE, until_newline, [$\n]}}, + IoServer ! {io_request, + self(), + IoServer, + {get_until, unicode, '', ?MODULE, until_newline, [$\n]}}, receive {io_reply, IoServer, Data} -> Data end.
-Note especially that the last element in the Request tuple ([$\n]) +
Note especially that the last element in the
+Request tuple ([$\n] ) is appended to the argument list when the function is called. The function should be called like - apply(Module, Function, [ State, Data | ExtraArgs ]) by the io_serverapply(Module, Function, [ State, Data | ExtraArgs ]) by the I/O serverA defined number of characters is requested using this Request:
+A fixed number of characters is requested using this
Request :{get_chars, Encoding, Prompt, N}
-
-- Encoding and Prompt as for get_until.
+- -
Encoding andPrompt as forget_until .- N is the number of characters to be read from the device.
+N is the number of characters to be read from the IO device.A single line (like in the example above) is requested with this Request:
+A single line (like in the example above) is requested with this
Request :{get_line, Encoding, Prompt}
-
-- Encoding and prompt as above.
+Encoding andPrompt as above.Obviously, get_chars and get_line could be implemented with the -get_until request (and indeed was originally), but demands for +
Obviously, the
-get_chars andget_line could be implemented with the +get_until request (and indeed they were originally), but demands for efficiency has made these additions necessary.The server replies to the client with an io_reply where the Reply +
The I/O server replies to the client with an
io_reply tuple where theReply element is one of:Data
@@ -269,16 +274,17 @@ element is one of:-
-- Data is the characters read, in either list or binary form - (depending on the io_server mode, see below).
-- Error describes the error to the client, which may do whatever it - wants with it. The Erlang io-module typically returns it as is.
-- eof is returned when input end is reached and no more data is +
- +
Data is the characters read, in either list or binary form + (depending on the I/O server mode, see below).- +
Error describes the error to the client, which may do whatever it + wants with it. The Erlangio + module typically returns it as is.eof is returned when input end is reached and no more data is available to the client process.For backward compatibility the following Requests should also be -handled by an io_server (these messages should not be present after +
For backward compatibility the following
Request s should also be +handled by an I/O server (these reqeusts should not be present after R15B of OTP):@@ -287,30 +293,30 @@ R15B of OTP):
{get_line, Prompt}
-These should behave as {get_until, latin1, Prompt, Module, Function, -ExtraArgs}, {get_chars, latin1, Prompt, N} and {get_line, latin1, -Prompt} respectively.
+These should behave as
{get_until, latin1, Prompt, Module, Function, +ExtraArgs} ,{get_chars, latin1, Prompt, N} and{get_line, latin1, +Prompt} respectively.- I/O-server modes - -Demands for efficiency when reading data from an io_server has not -only lead to the addition of the get_line and get_chars requests, but -has also added the concept of io_server options. No options are -mandatory to implement, but all io_servers in the Erlang standard -libraries honor the 'binary' option, which allows the Data in the -io_reply to be binary instead of in list form when possible. +
I/O-server Modes + +Demands for efficiency when reading data from an I/O server has not +only lead to the addition of the
+standard Erlang Unicode +format, i.e. UTF-8 (note that the function of theget_line andget_chars requests, but +has also added the concept of I/O server options. No options are +mandatory to implement, but all I/O servers in the Erlang standard +libraries honor thebinary option, which allows theData element of the +io_reply tuple to be a binary instead of a list when possible. If the data is sent as a binary, Unicode data will be sent in the -standard Erlang unicode -format, i.e. UTF-8 (note that the function in get_until still gets -list data regardless of the io_server mode).get_until request still gets +list data regardless of the I/O server mode). -Note that i.e. the
+get_until request allows for a function with the data specified as always being a list. Also the return value data from such a function can be of any type (as is indeed the case when an io:fread request is sent to an io_server). The client has to be prepared for data received as answers to those requests to be in a variety of forms, but the server should convert the results to binaries whenever possible (i.e. when the function supplied to get_until actually returns a list). The example shown later in this text does just that.Note that i.e. the
get_until request allows for a function with the data specified as always being a list. Also the return value data from such a function can be of any type (as is indeed the case when anio:fread request is sent to an I/O server). The client has to be prepared for data received as answers to those requests to be in a variety of forms, but the I/O server should convert the results to binaries whenever possible (i.e. when the function supplied toget_until actually returns a list). The example shown later in this text does just that.An I/O-server in binary mode will affect the data sent to the client, so that it has to be able to handle binary data. For convenience, it -is possible to set and retrieve the modes of an io_server using the -following I/O-requests:
+is possible to set and retrieve the modes of an I/O server using the +following I/O requests:{setopts, Opts} @@ -318,72 +324,72 @@ following I/O-requests:
-
-- Opts is a list of options in the format recognized by proplists (and - of course by the io_server itself).
+Opts is a list of options in the format recognized byproplists (and + of course by the I/O server itself).As an example, the io_server for the interactive shell (in group.erl) +
As an example, the I/O server for the interactive shell (in
group.erl ) understands the following options:-{binary, bool()} (or 'binary'/'list')
-
-{echo, bool()}
+{binary, boolean()} (or binary/list)
+{echo, boolean()}
{expand_fun, fun()}
-{encoding, 'unicode'/'latin1'} (or 'unicode'/'latin1') +{encoding, unicode/latin1} (or unicode/latin1)- of which the 'binary' and 'encoding' options are common for all -io_servers in OTP, while 'echo' and 'expand' is valid only for this -io_server. It's worth noting that the 'unicode' option notifies how -characters are actually put on the physical device, i.e. if the -terminal per se is unicode aware, it does not affect how characters +
- of which the
-binary andencoding options are common for all +I/O servers in OTP, whileecho andexpand are valid only for this +I/O server. It is worth noting that theunicode option notifies how +characters are actually put on the physical IO device, i.e. if the +terminal per se is Unicode aware, it does not affect how characters are sent in the I/O-protocol, where each request contains encoding information for the provided or returned data.The server should send one of the following as Reply:
+The I/O server should send one of the following as
Reply :ok
-
{error, Error}An error (preferably enotsup) is to be expected if the option is -not supported by the io_server (like if an 'echo' option is sent in a -setopt Request to a plain file).
+An error (preferably
-enotsup ) is to be expected if the option is +not supported by the I/O server (like if anecho option is sent in a +setopts request to a plain file).To retrieve options, this message is used:
+To retrieve options, this request is used:
getopts
-The 'getopts' message requests a complete list of all options -supported by the io_server as well as their current values.
+The
-getopts request asks for a complete list of all options +supported by the I/O server as well as their current values.The server replies:
+The I/O server replies:
OptList
-{error,Error} +{error, Error}-
- OptList is a list of tuples {Option, Value} where Option is always +
OptList is a list of tuples{Option, Value} whereOption is always an atom.- Multiple I/O requests +Multiple I/O Requests -The Request element can in itself contain several Requests by using +
The
Request element can in itself contain severalRequest s by using the following format:{requests, Requests}
-
-- Requests is a list of valid Request tuples for the protocol, they +
Requests is a list of validio_request tuples for the protocol, they shall be executed in the order in which they appear in the list and the execution should continue until one of the requests result in an error or the list is consumed. The result of the last request is sent back to the client.The server can for a list of requests send any of the valid results in +
The I/O server can for a list of requests send any of the valid results in the reply:
@@ -395,7 +401,7 @@ the reply:
- depending on the actual requests in the list.
- Optional I/O-requests +Optional I/O Requests The following I/O request is optional to implement and a client should be prepared for an error return:
@@ -403,47 +409,47 @@ should be prepared for an error return: {get_geometry, Geometry}-
-- Geometry is either the atom 'rows' or the atom 'columns'.
+Geometry is either the atomrows or the atomcolumns .The server should send the Reply as:
+The I/O server should send the
Reply as:{ok, N}
{error, Error}-
- N is the number of character rows or columns the device has, if - applicable to the device the io_server handles, otherwise {error, - enotsup} is a good answer.
+N is the number of character rows or columns the IO device has, if + applicable to the IO device the I/O server handles, otherwise{error, + enotsup} is a good answer.- Unimplemented request types: +Unimplemented Request Types -If an io_server encounters a request it does not recognize (i.e. the -io_request tuple is in the expected format, but the actual Request is -unknown), the server should send a valid reply with the error tuple:
+If an I/O server encounters a request it does not recognize (i.e. the +
io_request tuple is in the expected format, but the actualRequest is +unknown), the I/O server should send a valid reply with the error tuple:{error, request}
-This makes it possible to extend the protocol with optional messages +
This makes it possible to extend the protocol with optional requests and for the clients to be somewhat backwards compatible.
- diff --git a/lib/stdlib/doc/src/re.xml b/lib/stdlib/doc/src/re.xml index 2211bfb925..71a6e34513 100644 --- a/lib/stdlib/doc/src/re.xml +++ b/lib/stdlib/doc/src/re.xml @@ -96,12 +96,12 @@ subjects during the program's lifetime. Compiling once and executing many times is far more efficient than compiling each time one wants to match. -An annotated and working example io_server: +An Annotated and Working Example I/O Server -An io_server is any process capable of handling the protocol. There is -no generic io_server behavior, but could well be. The framework is +
An I/O server is any process capable of handling the I/O protocol. There is +no generic I/O server behavior, but could well be. The framework is simple enough, a process handling incoming requests, usually both -io_requests and other device-specific requests (for i.e. positioning , +I/O-requests and other IO device-specific requests (for i.e. positioning, closing etc.).
-Our example io_server stores characters in an ets table, making up a +
Our example I/O server stores characters in an ETS table, making up a fairly crude ram-file (it is probably not useful, but working).
The module begins with the usual directives, a function to start the -server and a main loop handling the requests:
+I/O server and a main loop handling the requests:-module(ets_io_server). @@ -486,18 +492,19 @@ loop(State) ->
The main loop receives messages from the client (which might be using -the io-module to send requests). For each request the function -request/2 is called and a reply is eventually sent using the reply/3 +the
-io module to send requests). +For each request the function +request/2 is called and a reply is eventually sent using thereply/3 function.The "private" message {From, rewind} results in the +
The "private" message
-{From, rewind} results in the current position in the pseudo-file to be reset to 0 (the beginning of -the "file"). This is a typical example of device-specific +the "file"). This is a typical example of IO device-specific messages not being part of the I/O-protocol. It is usually a bad idea -to embed such private messages in io_request tuples, as that might be +to embed such private messages inio_request tuples, as that might be confusing to the reader.Let's look at the reply function first...
+Let us look at the reply function first...
@@ -506,8 +513,8 @@ reply(From, ReplyAs, Reply) ->
-Simple enough, it sends the io_reply tuple back to the client, -providing the ReplyAs element received in the request along with the +
Simple enough, it sends the
io_reply tuple back to the client, +providing theReplyAs element received in the request along with the result of the request, as described above.Now look at the different requests we need to handle. First the @@ -525,18 +532,18 @@ request({put_chars, Encoding, Module, Function, Args}, State) -> end; -
The Encoding tells us how the characters in the message are +
The
+ETS table, so we convert them to lists using the +Encoding tells us how the characters in the request are represented. We want to store the characters as lists in the -ets-table, so we convert them to lists using the -unicode:characters_to_list/2 function. The conversion function -conveniently accepts the encoding types unicode or latin1, so we can -use the Encoding parameter directly.function. The conversion function +conveniently accepts the encoding types unicode:characters_to_list/2 unicode orlatin1 , so we can +useEncoding directly. -When Module, Function and Arguments are provided, we simply apply it +
When
-Module ,Function andArguments are provided, we simply apply it and do the same thing with the result as if the data was provided directly.Let's handle the requests for retrieving data too:
+Let us handle the requests for retrieving data too:
request({get_until, Encoding, _Prompt, M, F, As}, State) -> @@ -550,11 +557,11 @@ request({get_line, Encoding, _Prompt}, State) ->
Here we have cheated a little by more or less only implementing -get_until and using internal helpers to implement get_chars and -get_line. In production code, this might be to inefficient, but that +
+we start actually implementing the functionsget_until and using internal helpers to implementget_chars and +get_line . In production code, this might be too inefficient, but that of course depends on the frequency of the different requests. Before -we start actually implementing the functions put_chars/2 and -get_until/5, lets look into the few remaining requests:put_chars/2 and +get_until/5 , let us look into the few remaining requests:request({get_geometry,_}, State) -> @@ -567,18 +574,18 @@ request({requests, Reqs}, State) -> multi_request(Reqs, {ok, ok, State});
-The get_geometry request has no meaning for this io_server, so the -reply will be {error, enotsup}. The only option we handle is the -binary/list option, which is done in separate functions.
+The
-get_geometry request has no meaning for this I/O server, so the +reply will be{error, enotsup} . The only option we handle is the +binary /list option, which is done in separate functions.The multi-request tag (requests) is handled in a separate loop +
The multi-request tag (
-requests ) is handled in a separate loop function applying the requests in the list one after another, returning the last result.What's left is to handle backward compatibility and the file-module +
What is left is to handle backward compatibility and the
+nodes is no longer needed). Note that the I/O server will not work with +a simplefile module (which uses the old requests until backward compatibility with pre-R13 -nodes is no longer needed). Note that the io_server will not work with -a simple file:write if these are not added:file:write/2 if these are not added:request({put_chars,Chars}, State) -> @@ -593,7 +600,7 @@ request({get_until, Prompt,M,F,As}, State) -> request({get_until,latin1,Prompt,M,F,As}, State);
-Ok, what's left now is to return {error, request} if the request is +
OK, what is left now is to return
{error, request} if the request is not recognized:@@ -601,7 +608,7 @@ request(_Other, State) -> {error, {error, request}, State}.
-Let's move further and actually handle the different requests, first +
Let us move further and actually handle the different requests, first the fairly generic multi-request type:
@@ -615,10 +622,10 @@ multi_request([], Result) ->
We loop through the requests one at the time, stopping when we either encounter an error or the list is exhausted. The last return value is -sent back to the client (it's first returned to the main loop and then -sent back by the function io_reply).
+sent back to the client (it is first returned to the main loop and then +sent back by the functionio_reply ). -The getopt and setopt requests are also simple to handle, we just +
The
getopts andsetopts requests are also simple to handle, we just change or read our state record:@@ -656,24 +663,24 @@ getopts(#state{mode=M} = S) -> end}],S}.
-As a convention, all io_servers handle both {setopts, [binary]}, -{setopts, [list]} and {setopts,[{binary, bool()}]}, hence the trick -with proplists:substitute_negations/2 and proplists:unfold/1. If -invalid options are sent to us, we send {error,enotsup} back to the +
As a convention, all I/O servers handle both
-{setopts, [binary]} , +{setopts, [list]} and{setopts,[{binary, boolean()}]} , hence the trick +withproplists:substitute_negations/2 andproplists:unfold/1 . If +invalid options are sent to us, we send{error, enotsup} back to the client.The getopts request should return a list of {Option, Value} tuples, +
The
-getopts request should return a list of{Option, Value} tuples, which has the twofold function of providing both the current values -and the available options of this io_server. We have only one option, +and the available options of this I/O server. We have only one option, and hence return that.So far our io_server has been fairly generic (except for the rewind -request handled in the main loop and the creation of an ets table). -Most io_servers contain code similar to what's above.
+So far our I/O server has been fairly generic (except for the
rewind +request handled in the main loop and the creation of an ETS table). +Most I/O servers contain code similar to the one above.To make the example runnable, we now start implementing the actual -reading and writing of the data to/from the ets-table. First the -put_chars function:
+reading and writing of the data to/from the ETS table. First the +put_chars/3 function:put_chars(Chars, #state{table = T, position = P} = State) -> @@ -686,10 +693,10 @@ put_chars(Chars, #state{table = T, position = P} = State) ->
-We already have the data as (Unicode) lists and therefore just split the list in runs of a predefined size and put each run in the table at the current position (and forward). The functions -split_data/3 and apply_update/2 are implemented below.
+split_data/3 andapply_update/2 are implemented below. -Now we want to read data from the table. The get_until function reads -data and applies the function until it says it's done. The result is +
Now we want to read data from the table. The
get_until/5 function reads +data and applies the function until it says it is done. The result is sent back to the client:@@ -700,11 +707,12 @@ get_until(Encoding, Mod, Func, As, if M =:= binary -> {ok, - unicode:characters_to_binary(Data,unicode,Encoding), + unicode:characters_to_binary(Data, unicode, Encoding), State#state{position = NewP}}; true -> case check(Encoding, - unicode:characters_to_list(Data, unicode)) of + unicode:characters_to_list(Data, unicode)) + of {error, _} = E -> {error, E, State}; List -> @@ -730,24 +738,24 @@ get_loop(M,F,A,T,P,C) -> end.
-Here we also handle the mode (binary or list) that can be set by -the setopts request. By default, all OTP io_servers send data back to -the client as lists, but switching mode to binary might increase -efficiency if the server handles it in an appropriate way. The -implementation of get_until is hard to get efficient as the supplied -function is defined to take lists as arguments, but get_chars and -get_line can be optimized for binary mode. This example does not +
Here we also handle the mode (
@@ -768,13 +776,13 @@ check(latin1, List) -> end.binary orlist ) that can be set by +thesetopts request. By default, all OTP I/O servers send data back to +the client as lists, but switching mode tobinary might increase +efficiency if the I/O server handles it in an appropriate way. The +implementation ofget_until is hard to get efficient as the supplied +function is defined to take lists as arguments, butget_chars and +get_line can be optimized for binary mode. This example does not optimize anything however. It is important though that the returned data is of the right type depending on the options set, so we convert the lists to binaries in the correct encoding if possible -before returning. The function supplied in the get_until request may, +before returning. The function supplied in theget_until request tuple may, as its final result return anything, so only functions actually returning lists can get them converted to binaries. If the request -contained the encoding tag unicode, the lists can contain all unicode +contained the encoding tagunicode , the lists can contain all Unicode codepoints and the binaries should be in UTF-8, if the encoding tag -was latin1, the client should only get characters in the range -0..255. The function check/2 takes care of not returning arbitrary -unicode codepoints in lists if the encoding was given as latin1. If +waslatin1 , the client should only get characters in the range +0..255. The functioncheck/2 takes care of not returning arbitrary +Unicode codepoints in lists if the encoding was given aslatin1 . If the function did not return a list, the check cannot be performed and the result will be that of the supplied function untouched.The function check takes care of providing an error tuple if unicode +
The function check takes care of providing an error tuple if Unicode codepoints above 255 is to be returned if the client requested latin1.
-The two functions until_newline/3 and until_enough/3 are helpers used -together with the get_until function to implement get_chars and -get_line (inefficiently):
+The two functions
until_newline/3 anduntil_enough/3 are helpers used +together with theget_until/5 function to implementget_chars and +get_line (inefficiently):until_newline([],eof,_MyStopCharacter) -> @@ -782,7 +790,9 @@ until_newline([],eof,_MyStopCharacter) -> until_newline(ThisFar,eof,_MyStopCharacter) -> {done,ThisFar,[]}; until_newline(ThisFar,CharList,MyStopCharacter) -> - case lists:splitwith(fun(X) -> X =/= MyStopCharacter end, CharList) of + case + lists:splitwith(fun(X) -> X =/= MyStopCharacter end, CharList) + of {L,[]} -> {more,ThisFar++L}; {L2,[MyStopCharacter|Rest]} -> @@ -802,10 +812,10 @@ until_enough(ThisFar,CharList,_N) ->
As can be seen, the functions above are just the type of functions -that should be provided in get_until requests.
+that should be provided inget_until requests.Now we only need to read and write the table in an appropriate way to -complete the server:
+complete the I/O server:get(P,Tab) -> @@ -847,13 +857,13 @@ apply_update(Table, {Row, Col, List}) -> end.
-The table is read or written in chunks of ?CHARS_PER_REC, overwriting +
The table is read or written in chunks of
?CHARS_PER_REC , overwriting when necessary. The implementation is obviously not efficient, it is just working.This concludes the example. It is fully runnable and you can read or -write to the io_server by using i.e. the io_module or even the file -module. It's as simple as that to implement a fully fledged io_server +write to the I/O server by using i.e. the
io module or even thefile +module. It is as simple as that to implement a fully fledged I/O server in Erlang.When the unicode option is given, the regular expression should be given as a valid unicode
+charlist() , otherwise as any validiodata() .When the unicode option is given, the regular expression should be given as a valid Unicode
charlist() , otherwise as any validiodata() .
The options have the following meanings: - unicode - The regular expression is given as a unicode
+charlist() and the resulting regular expression code is to be run against a valid unicodecharlist() subject.- The regular expression is given as a Unicode
charlist() and the resulting regular expression code is to be run against a valid Unicodecharlist() subject.anchored - The pattern is forced to be "anchored", that is, it is constrained to match only at the first matching point in the string that is being searched (the "subject string"). This effect can also be achieved by appropriate constructs in the pattern itself.
@@ -478,7 +478,7 @@ This option makes it possible to include comments inside complicated patterns. N caseless Replaces the matched part of the
string with the contents of Subject . Replacement The permissible options are the same as for
re:run/3 , except that thecapture option is not allowed. Instead a{return, is present. The default return type isReturnType }iodata , constructed in a - way to minimize copying. Theiodata result can be used directly in many i/o-operations. If a flatlist() is + way to minimize copying. Theiodata result can be used directly in many I/O-operations. If a flatlist() is desired, specify{return, list} and if a binary is preferred, specify{return, binary} .As in the
re:run/3 function, anmp() compiled diff --git a/lib/stdlib/doc/src/unicode.xml b/lib/stdlib/doc/src/unicode.xml index 1f6cbaccd7..d235f3e180 100644 --- a/lib/stdlib/doc/src/unicode.xml +++ b/lib/stdlib/doc/src/unicode.xml @@ -32,9 +32,9 @@unicode Functions for converting Unicode characters - @@ -48,13 +48,13 @@This module contains functions for converting between different character representations. Basically it converts between iso-latin-1 characters and Unicode ditto, but it can also convert between different Unicode encodings (like UTF-8, UTF-16 and UTF-32).
+This module contains functions for converting between different character representations. Basically it converts between ISO-latin-1 characters and Unicode ditto, but it can also convert between different Unicode encodings (like UTF-8, UTF-16 and UTF-32).
The default Unicode encoding in Erlang is in binaries UTF-8, which is also the format in which built in functions and libraries in OTP expect to find binary Unicode data. In lists, Unicode data is encoded as integers, each integer representing one character and encoded simply as the Unicode codepoint for the character.
-Other Unicode encodings than integers representing codepoints or UTF-8 in binaries are referred to as "external encodings". The iso-latin-1 encoding is in binaries and lists referred to as latin1-encoding.
+Other Unicode encodings than integers representing codepoints or UTF-8 in binaries are referred to as "external encodings". The ISO-latin-1 encoding is in binaries and lists referred to as latin1-encoding.
It is recommended to only use external encodings for communication with external entities where this is required. When working inside the Erlang/OTP environment, it is recommended to keep binaries in UTF-8 when representing Unicode characters. Latin1 encoding is supported both for backward compatibility and for communication with external entities not supporting Unicode character sets.
- A binary() with characters encoded in the UTF-8 coding standard.
+A
binary() with characters encoded in the UTF-8 coding standard.- An integer() representing a valid unicode codepoint.
+An
integer() representing a valid Unicode codepoint.@@ -63,7 +63,7 @@ - A unicode_binary is allowed as the tail of the list.
+A
unicode_binary() is allowed as the tail of the list.@@ -85,7 +85,7 @@ - A
+binary() with characters coded in iso-latin-1.A
binary() with characters coded in ISO-latin-1.@@ -110,7 +110,9 @@ Identify UTF byte order marks in a binary. - A binary() of byte_size 4 or more. ++ A binary() such thatbyte_size( . +Bin ) >= 4Check for a UTF byte order mark (BOM) in the beginning of a @@ -126,7 +128,7 @@
Convert a collection of characters to list of Unicode characters - Same as characters_to_list(
+Data ,unicode).Same as
characters_to_list( .Data , unicode)@@ -134,8 +136,8 @@ Convert a collection of characters to list of Unicode characters - This function converts a possibly deep list of integers and - binaries into a list of integers representing unicode +
Converts a possibly deep list of integers and + binaries into a list of integers representing Unicode characters. The binaries in the input may have characters encoded as latin1 (0 - 255, one character per byte), in which case the
parameter should be given as @@ -148,18 +150,18 @@ InEncoding If
is InEncoding latin1 , theparameter corresponds to the Data iodata() type, but forunicode , theparameter can contain integers greater than 255 - (unicode characters beyond the iso-latin-1 range), which would + (Unicode characters beyond the ISO-latin-1 range), which would make it invalid as Data iodata() .The purpose of the function is mainly to be able to convert - combinations of unicode characters into a pure unicode + combinations of Unicode characters into a pure Unicode string in list representation for further processing. For writing the data to an external entity, the reverse function
-characters_to_binary/3 + marker="#characters_to_binary/3">characters_to_binary/3 comes in handy.The option
unicode is an alias forutf8 , as this is the +The option
unicode is an alias forutf8 , as this is the preferred encoding for Unicode characters in binaries.utf16 is an alias for{utf16,big} andutf32 is an alias for{utf32,big} . Thebig @@ -167,7 +169,7 @@ encoding.If for some reason, the data cannot be converted, either - because of illegal unicode/latin1 characters in the list, or + because of illegal Unicode/latin1 characters in the list, or because of invalid UTF encoding in any binaries, an error tuple is returned. The error tuple contains the tag
+ list and whatever is left to decode is simply returned as is.error , a list representing the characters that could be @@ -176,7 +178,7 @@ last part is mostly for debugging as it still constitutes a possibly deep and/or mixed list, not necessarily of the same depth as the original data. The error occurs when traversing the - list and whatever's left to decode is simply returned as is.However, if the input
is a pure binary, the third part of the error tuple is guaranteed to be a binary as @@ -191,7 +193,7 @@ of a Unicode type, an error occurs whenever an integer Data
- greater than
+ (the maximum Unicode character),16#10FFFF - (the maximum unicode character),
If any parameters are of the wrong type, the list structure
- is invalid (a number as tail) or the binaries does not contain
+ is invalid (a number as tail) or the binaries do not contain
whole bytes (bit-strings), a
Same as characters_to_binary(Data, unicode, unicode).
+Same as
Same as characters_to_binary(
Same as
This function behaves as
Behaves as
Errors and exceptions occur as in
Create an UTF byte order mark (BOM) as a binary from the +
Create a UTF byte order mark (BOM) as a binary from the
supplied
The function returns
It can be noted that the BOM for UTF-8 is seldom used, and it
is really not a byte order mark. There are obviously no
diff --git a/lib/stdlib/doc/src/unicode_usage.xml b/lib/stdlib/doc/src/unicode_usage.xml
index e93d49b24a..6131a7c6d1 100644
--- a/lib/stdlib/doc/src/unicode_usage.xml
+++ b/lib/stdlib/doc/src/unicode_usage.xml
@@ -33,10 +33,10 @@
Implementing support for Unicode character sets is an ongoing process. The Erlang Enhancement Proposal (EEP) 10 outlines the basics of Unicode support and also specifies a default encoding in binaries that all Unicode-aware modules should handle in the future.
-The functionality described in EEP10 is implemented in Erlang/OTP as of R13A, but that's by no means the end of it. More functionality will be needed in the future and more OTP-libraries might need updating to cope with Unicode data.
+The functionality described in EEP10 is implemented in Erlang/OTP as of R13A, but that is by no means the end of it. More functionality will be needed in the future and more OTP-libraries might need updating to cope with Unicode data.
This guide outlines the current Unicode support and gives a couple of recipes for working with Unicode data.
Unicode is a standard defining codepoints (numbers) for all known, living or dead, scripts. In principle, every known symbol used in any language has a Unicode codepoint.
Unicode codepoints are defined and published by the Unicode Consortium, which is a non profit organization.
Support for Unicode is increasing throughout the world of computing, as the benefits of one common character set are overwhelming when programs are used in a global environment.
@@ -56,19 +56,20 @@Additionally, the codepoint 16#FEFF is used for byte order marks (BOM's) and use of that character is not encouraged in other contexts than that. It actually is valid though, as the character "ZWNBS" (Zero Width Non Breaking Space). BOM's are used to identify encodings and byte order for programs where such parameters are not known in advance. Byte order marks are more seldom used than one could expect, but their use is becoming more widely spread as they provide the means for programs to make educated guesses about the Unicode format of a certain file.
In Erlang, strings are actually lists of integers. A string is defined to be encoded in the ISO-latin-1 (ISO8859-1) character set, which is, codepoint by codepoint, a sub-range of the Unicode character set.
The standard list encoding for strings is therefore easily extendible to cope with the whole Unicode range: A Unicode string in Erlang is simply a list containing integers, each integer being a valid Unicode codepoint and representing one character in the Unicode character set.
-Regular Erlang strings in ISO-latin-1 are a subset of their Unicode strings.
+Regular Erlang strings in ISO-latin-1 are a subset of their Unicode +strings.
-Binaries on the other hand are more troublesome. For performance reasons, programs often store textual data in binaries instead of lists, mainly because they are more compact (one byte per character instead of two words per character, as is the case with lists). Using erlang:list_to_binary/1, a regular Erlang string can be converted into a binary, effectively using the ISO-latin-1 encoding in the binary - one byte per character. This is very convenient for those regular Erlang strings, but cannot be done for Unicode lists.
+Binaries on the other hand are more troublesome. For performance reasons, programs often store textual data in binaries instead of lists, mainly because they are more compact (one byte per character instead of two words per character, as is the case with lists). Using
As the UTF-8 encoding is widely spread and provides the most compact storage, it is selected as the standard encoding of Unicode characters in binaries for Erlang.
The standard binary encoding is used whenever a library function in Erlang should cope with Unicode data in binaries, but is of course not enforced when communicating externally. Functions and bit-syntax exist to encode and decode both UTF-8, UTF-16 and UTF-32 in binaries. Library functions dealing with binaries and Unicode in general, however, only deal with the default encoding.
-Character data may be combined from several sources, sometimes available in a mix of strings and binaries. Erlang has for long had the concept of iodata or iolists, where binaries and lists can be combined to represent a sequence of bytes. In the same way, the Unicode aware modules often allow for combinations of binaries and lists where the binaries have characters encoded in UTF-8 and the lists contain such binaries or numbers representing Unicode codepoints:
+Character data may be combined from several sources, sometimes available in a mix of strings and binaries. Erlang has for long had the concept of
unicode_binary() = binary() with characters encoded in UTF-8 coding standard
-unicode_char() = integer() >= 0 representing valid unicode codepoint
+unicode_char() = integer() >= 0 representing valid Unicode codepoint
chardata() = charlist() | unicode_binary()
@@ -76,16 +77,18 @@ charlist() = [unicode_char() | unicode_binary() | charlist()]
a unicode_binary is allowed as the tail of the list
The module
-external_unicode_binary() = binary() with characters coded in a user specified Unicode
- encoding other than UTF-8 (UTF-16 or UTF-32)
+external_unicode_binary() = binary() with characters coded in
+ a user specified Unicode encoding other than UTF-8 (UTF-16 or UTF-32)
external_chardata() = external_charlist() | external_unicode_binary()
-external_charlist() = [unicode_char() | external_unicode_binary() | external_charlist()]
+external_charlist() = [unicode_char() |
+ external_unicode_binary() |
+ external_charlist()]
an external_unicode_binary() is allowed as the tail of the list
For source code, there is an extension to the \OOO (backslash -followed by three octal numbers) and \xHH (backslash followed by 'x', -followed by two hexadecimal characters) syntax, namely \x{H ...} (a -backslash followed by an 'x', followed by left curly bracket, any +
For source code, there is an extension to the
In the shell, if using a Unicode input device, '$' can be followed directly by a Unicode character producing an integer. In the following example the codepoint of a Cyrillic 's' is output:
+In the shell, if using a Unicode input device,
7> $с. 1089
The interactive Erlang shell, when started towards a terminal or started using the
On Windows®, proper operation requires that a suitable font is installed and selected for the Erlang application to use. If no suitable font is available on your system, try installing the DejaVu fonts (dejavu-fonts.org), which are freely available and then select that font in the Erlang shell application.
-On Unix®-like operating systems, the terminal should be able to handle UTF-8 on input and output (modern versions of XTerm, KDE konsole and the Gnome terminal do for example) and your locale settings have to be proper. As an example, my LANG environment variable is set as this:
+On Windows®, proper operation requires that a suitable font is installed and selected for the Erlang application to use. If no suitable font is available on your system, try installing the DejaVu fonts (
On Unix®-like operating systems, the terminal should be able to handle UTF-8 on input and output (modern versions of XTerm, KDE konsole and the Gnome terminal do for example) and your locale settings have to be proper. As an example, my
$ echo $LANG en_US.UTF-8-
Actually, most systems handle the LC_CTYPE variable before LANG, so if that is set, it has to be set to UTF-8:
+Actually, most systems handle the
$ echo $LC_CTYPE en_US.UTF-8-
The LANG or LC_CTYPE setting should be consistent with what the terminal is capable of, there is no portable way for Erlang to ask the actual terminal about its UTF-8 capacity, we have to rely on the language and character type settings.
+The
To investigate what Erlang thinks about the terminal, the
$ LC_CTYPE=en_US.ISO-8859-1 erl -Erlang R13A (erts-5.10) [source] [64-bit] [smp:4:4] [rq:4] [async-threads:0] [kernel-poll:false] +Erlang R16B (erts-5.10) [source] [async-threads:0] [hipe] [kernel-poll:false] Eshell V5.10 (abort with ^G) -1> lists:keyfind(encoding,1,io:getopts()). +1> lists:keyfind(encoding, 1, io:getopts()). {encoding,latin1} 2> q(). ok $ LC_CTYPE=en_US.UTF-8 erl -Erlang R13A (erts-5.10) [source] [64-bit] [smp:4:4] [rq:4] [async-threads:0] [kernel-poll:false] +Erlang R16B (erts-5.10) [source] [async-threads:0] [hipe] [kernel-poll:false] Eshell V5.10 (abort with ^G) -1> lists:keyfind(encoding,1,io:getopts()). +1> lists:keyfind(encoding, 1, io:getopts()). {encoding,unicode} 2>
When (finally?) everything is in order with the locale settings, fonts and the terminal emulator, you probably also have discovered a way to input characters in the script you desire. For testing, the simplest way is to add some keyboard mappings for other languages, usually done with some applet in your desktop environment. In my KDE environment, I start the KDE Control Center (Personal Settings), select "Regional and Accessibility" and then "Keyboard Layout". On Windows XP®, I start Control Panel->Regional and Language Options, select the Language tab and click the Details... button in the square named "Text services and input Languages". Your environment probably provides similar means of changing the keyboard layout. Make sure you have a way to easily switch back and forth between keyboards if you are not used to this, entering commands using a Cyrillic character set is, as an example, not easily done in the Erlang shell.
Now you are set up for some Unicode input and output. The simplest thing to do is of course to enter a string in the shell:
$ erl +Erlang R16B (erts-5.10) [source] [async-threads:0] [hipe] [kernel-poll:false] + Eshell V5.10 (abort with ^G) 1> lists:keyfind(encoding, 1, io:getopts()). {encoding,unicode} @@ -166,6 +171,9 @@ ok 4>
While strings can be input as Unicode characters, the language elements are still limited to the ISO-latin-1 character set. Only character constants and strings are allowed to be beyond that range:
+$ erl +Erlang R16B (erts-5.10) [source] [async-threads:0] [hipe] [kernel-poll:false] + Eshell V5.10 (abort with ^G) 1> $ξ 958 @@ -174,7 +182,7 @@ Eshell V5.10 (abort with ^G) 2>
Most modern operating systems support Unicode file names in some way or another. There are several different ways to do this and Erlang by default treats the different approaches differently:
A raw file name is not a list, but a binary. Many non core applications still do not handle file names given as binaries, why such raw names are avoided by default. This means that systems having implemented Unicode file naming through transparent file systems and an UTF-8 convention, do not by default have Unicode file naming turned on. Explicitly turning Unicode file name handling on for these types of systems is considered experimental.
The Unicode file naming support was introduced with OTP release R14B01. A VM operating in Unicode file mode can work with files having names in any language or character set (as long as it's supported by the underlying OS and file system). The Unicode character list is used to denote file or directory names and if the file system content is listed, you will also be able to get Unicode lists as return value. The support lies in the Kernel and STDLIB modules, why most applications (that does not explicitly require the file names to be in the ISO-latin-1 range) will benefit from the Unicode support without change.
+The Unicode file naming support was introduced with OTP release R14B01. A VM operating in Unicode file mode can work with files having names in any language or character set (as long as it is supported by the underlying OS and file system). The Unicode character list is used to denote file or directory names and if the file system content is listed, you will also be able to get Unicode lists as return value. The support lies in the Kernel and STDLIB modules, why most applications (that does not explicitly require the file names to be in the ISO-latin-1 range) will benefit from the Unicode support without change.
On Operating systems with mandatory Unicode file names, this means that you more easily conform to the file names of other (non Erlang) applications, and you can also process file names that, at least on Windows, were completely inaccessible (due to having names that could not be represented in ISO-latin-1). Also you will avoid creating incomprehensible file names on MacOSX as the vfs layer of the OS will accept all your file names as UTF-8 and will not rewrite them.
@@ -199,32 +207,32 @@ Eshell V5.10 (abort with ^G)It is worth noting that the file
Erlang drivers and NIF shared objects still can not be named with names containing codepoints beyond 127. This is a known limitation to be removed in a future release. Erlang modules however can, but it is definitely not a good idea and is still considered experimental.
Raw file names is introduced together with Unicode file name support in erts-5.8.2 (OTP R14B01). The reason "raw file names" is introduced in the system is to be able to consistently represent file names given in different encodings on the same system. Having the VM automatically translate a file name that is not in UTF-8 to a list of Unicode characters might seem practical, but this would open up for both duplicate file names and other inconsistent behavior. Consider a directory containing a file named "björn" in ISO-latin-1, while the Erlang VM is operating in Unicode file name mode (and therefore expecting UTF-8 file naming). The ISO-latin-1 name is not valid UTF-8 and one could be tempted to think that automatic conversion in for example
The core system of Erlang (Kernel and STDLIB) accepts raw file names except for loadable drivers and executables invoked using
To force Unicode file name translation mode on systems where this is not the default is considered experimental in OTP R14B01 due to the raw file names possibly being a new experience to the programmer and that the non core applications of OTP are not tested for compliance with raw file names yet. Unicode file name translation is expected to be default in future releases.
-If working with raw file names, one can still conform to the encoding convention of the Erlang VM by using the
If working with raw file names, one can still conform to the encoding convention of the Erlang VM by using the
Even if you are operating without Unicode file naming translation automatically done by the VM, you can access and create files with names in UTF-8 encoding by using raw file names encoded as UTF-8. Enforcing the UTF-8 encoding regardless of the mode the Erlang VM is started in might, in some circumstances be a good idea, as the convention of using UTF-8 file names is spreading.
MacOSXs vfs layer enforces UTF-8 file names in a quite aggressive way. Older versions did this by simply refusing to create non UTF-8 conforming file names, while newer versions replace offending bytes with the sequence "%HH", where HH is the original character in hexadecimal notation. As Unicode translation is enabled by default on MacOSX, the only way to come up against this is to either start the VM with the
MacOSX also reorganizes the names of files so that the representation of accents etc is denormalized, i.e. the character
Environment variables and their interpretation is handled much in the same way as file names. If Unicode file names are enabled, environment variables as well as parameters to the Erlang VM are expected to be in Unicode.
If Unicode file names are enabled, the calls to
On Unix-like operating systems, parameters are expected to be UTF-8 without translation if Unicode file names are enabled.
Most of the modules in Erlang/OTP are of course Unicode-unaware in the sense that they have no notion of Unicode and really shouldn't have. Typically they handle non-textual or byte-oriented data (like
Most of the modules in Erlang/OTP are of course Unicode-unaware in the sense that they have no notion of Unicode and really should not have. Typically they handle non-textual or byte-oriented data (like
Modules that actually handle textual data (like
Fortunately, most textual data has been stored in lists and range checking has been sparse, why modules like
Some modules are however changed to be explicitly Unicode-aware. These modules include:
@@ -237,7 +245,7 @@ Eshell V5.10 (abort with ^G)The
I/O-servers throughout the system are able both to handle Unicode data and has options for converting data upon actual output or input to/from the device. As shown earlier, the
The actual reading and writing of files with Unicode data is however not best done with the
The module
When starting with Unicode, one often stumbles over some common issues. I try to outline some methods of dealing with Unicode data in this section.
A common method of identifying encoding in text-files is to put a byte order mark (BOM) first in the file. The BOM is the codepoint 16#FEFF encoded in the same way as the rest of the file. If such a file is to be read, the first few bytes (depending on encoding) is not part of the actual text. This code outlines how to open a file which is believed to have a BOM and set the files encoding and position for further sequential reading (preferably using the
open_bom_file_for_reading(File) ->
@@ -268,7 +276,7 @@ open_bom_file_for_reading(File) ->
io:setopts(F,[{encoding,Type}]),
{ok,F}.
-The
The
To open a file for writing and putting the BOM first is even simpler:
open_bom_file_for_writing(File,Encoding) ->
@@ -280,8 +288,8 @@ open_bom_file_for_writing(File,Encoding) ->
In both cases the file is then best processed using the io module, as the functions in io can handle codepoints beyond the ISO-latin-1 range.
When reading and writing to Unicode-aware entities, like the User or a file opened for Unicode translation, you will probably want to format text strings using the functions in
When reading and writing to Unicode-aware entities, like the User or a file opened for Unicode translation, you will probably want to format text strings using the functions in
1> io:format("~ts~n",[<<"åäö"/utf8>>]). åäö @@ -289,21 +297,24 @@ ok 2> io:format("~s~n",[<<"åäö"/utf8>>]). åäö ok-
Obviously the second
As long as the data is always lists, the "t" modifier can be used for any string, but when binary data is involved, care must be taken to make the tight choice of formatting characters.
-The function
Obviously the second
As long as the data is always lists, the
The function
+$ erl +Erlang R16B (erts-5.10) [source] [async-threads:0] [hipe] [kernel-poll:false] + Eshell V5.10 (abort with ^G) 1> io_lib:format("~ts~n", ["θνιψοδε"]). ["θνιψοδε","\n"] 2> io:put_chars(io_lib:format("~ts~n", ["θνιψοδε"])). θνιψοδε ok-
The Unicode string is returned as a Unicode list, which is recognized as such since the Erlang shell uses the Unicode encoding. The Unicode list is valid input to the
The Unicode string is returned as a Unicode list, which is recognized as such since the Erlang shell uses the Unicode encoding. The Unicode list is valid input to the
While it's strongly encouraged that the actual encoding of characters in binary data is known prior to processing, that is not always possible. On a typical Linux® system, there is a mix of UTF-8 and ISO-latin-1 text files and there are seldom any BOM's in the files to identify them.
+While it iss strongly encouraged that the actual encoding of characters in binary data is known prior to processing, that is not always possible. On a typical Linux® system, there is a mix of UTF-8 and ISO-latin-1 text files and there are seldom any BOM's in the files to identify them.
UTF-8 is designed in such a way that ISO-latin-1 characters with numbers beyond the 7-bit ASCII range are seldom considered valid when decoded as UTF-8. Therefore one can usually use heuristics to determine if a file is in UTF-8 or if it is encoded in ISO-latin-1 (one byte per character) encoding. The
heuristic_encoding_bin(Bin) when is_binary(Bin) ->
--
cgit v1.2.3