From 4b42bf9358eca2c4597837e87dd10e49c1b60bc7 Mon Sep 17 00:00:00 2001 From: Hans Bolinder Date: Fri, 28 Dec 2012 10:28:16 +0100 Subject: Clean up some of the Unicode documentation --- lib/kernel/doc/src/file.xml | 2 +- lib/stdlib/doc/src/io.xml | 85 ++++--- lib/stdlib/doc/src/io_protocol.xml | 476 ++++++++++++++++++----------------- lib/stdlib/doc/src/re.xml | 6 +- lib/stdlib/doc/src/unicode.xml | 71 +++--- lib/stdlib/doc/src/unicode_usage.xml | 105 ++++---- 6 files changed, 384 insertions(+), 361 deletions(-) (limited to 'lib') diff --git a/lib/kernel/doc/src/file.xml b/lib/kernel/doc/src/file.xml index d7bdcef53c..536b98b5f5 100644 --- a/lib/kernel/doc/src/file.xml +++ b/lib/kernel/doc/src/file.xml @@ -110,7 +110,7 @@

As returned by file:open/2, - a process handling IO protocols.

+ a process handling I/O-protocols.

diff --git a/lib/stdlib/doc/src/io.xml b/lib/stdlib/doc/src/io.xml index ed425ce723..24cc4714d0 100644 --- a/lib/stdlib/doc/src/io.xml +++ b/lib/stdlib/doc/src/io.xml @@ -28,9 +28,9 @@ io - Standard IO Server Interface Functions + Standard I/O Server Interface Functions -

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 ok if they are successful, or exit if they are not.

In the following description, all functions have an optional @@ -45,10 +45,9 @@ marker="#put_chars/2">put_chars function should be in the unicode:chardata() format. This means that programs supplying binaries to this function need to convert them to UTF-8 - before trying to output the data on an - io_device().

+ before trying to output the data on an IO device.

-

If an io_device() is set in binary mode, the functions If an IO device is set in binary mode, the functions get_chars and get_line may return binaries instead of lists. The binaries will, as of R13A, be encoded in @@ -68,9 +67,9 @@ -

Either standard_io, standard_error, a +

An IO device. Either standard_io, standard_error, a registered name, or a pid handling IO protocols (returned from - file:open/2).

+ file:open/2).

@@ -107,11 +106,11 @@ - Get the number of columns of a device + Get the number of columns of an IO device

Retrieves the number of columns of the IoDevice (i.e. the width of a terminal). The function - only succeeds for terminal devices, for all other devices + only succeeds for terminal devices, for all other IO devices the function returns {error, enotsup}

@@ -120,7 +119,7 @@ Write a list of characters -

Writes the characters of CharData to the io_server() +

Writes the characters of CharData to the I/O server (IoDevice).

@@ -143,11 +142,11 @@ Data -

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).

eof @@ -172,11 +171,11 @@ Data

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).

eof @@ -195,7 +194,7 @@ Get the supported options and values from an I/O-server -

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 and get_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 and get_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.

{echo, boolean()} @@ -261,10 +260,10 @@ {encoding, latin1 | unicode} -

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.

@@ -380,7 +379,7 @@ ok
applicable, it is used for both the field width and precision. The default padding character is ' ' (space).

Mod is the control sequence modifier. It is either a - single character (currently only 't', for unicode translation, + single character (currently only t, for Unicode translation, is supported) that changes the interpretation of Data.

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 (t) is in effect, the integer argument can be any number representing a - valid unicode codepoint, otherwise it should be an integer + valid Unicode codepoint, otherwise it should be an integer less than or equal to 255, otherwise it is masked with 16#FF:

 1> io:fwrite("~tc~n",[1024]).
@@ -442,7 +441,7 @@ ok

Prints the argument with the string syntax. The argument is, if no Unicode translation modifier is present, an - iolist(), a binary, or an atom. If the Unicode translation modifier ('t') is in effect, the argument is unicode:chardata(), meaning that binaries are in UTF-8. The characters + iolist(), a binary, or an atom. If the Unicode translation modifier (t) is in effect, the argument is unicode:chardata(), meaning that binaries are in UTF-8. The characters are printed without quotes. The string is first truncated by the given precision and then padded and justified to the given field width. The default precision is the field width.

@@ -601,7 +600,7 @@ ok #

Like B, but prints the number with an Erlang style - '#'-separated base prefix.

+ #-separated base prefix.

 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. F is the field width of the input field, M is an optional - translation modifier (of which 't' is the only currently + translation modifier (of which t is the only currently supported, meaning Unicode translation) and C determines the type of control sequence.

@@ -708,8 +707,8 @@ ok -

An optional sign character is expected. A sign - character '-' gives the return value -1. Sign - character '+' or none gives 1. The field width + character - gives the return value -1. Sign + character + or none gives 1. The field width parameter is ignored. Leading white-space characters are not skipped.

@@ -811,11 +810,11 @@ enter>: alan : joe - Get the number of rows of a device + Get the number of rows of an IO device

Retrieves the number of rows of the IoDevice (i.e. the height of a terminal). The function - only succeeds for terminal devices, for all other devices + only succeeds for terminal devices, for all other IO devices the function returns {error, enotsup}

@@ -832,7 +831,7 @@ enter>: alan : joeOptions argument of the erl_scan:tokens/4 function. The data is tokenized as if it were a - sequence of Erlang expressions until a final '.' is + sequence of Erlang expressions until a final dot (.) is reached. This token is also returned. It returns:

{ok, Tokens, EndLine} @@ -872,7 +871,7 @@ enter>1.0er. Options argument of the erl_scan:tokens/4 function. The data is tokenized as if it were an Erlang form - one of the valid Erlang expressions in an - Erlang source file - until a final '.' is reached. + Erlang source file - until a final dot (.) is reached. This last token is also returned. The return values are the same as for scan_erl_exprs/1,2,3 above.

@@ -892,7 +891,7 @@ enter>1.0er. Options is passed on as the Options argument of the erl_scan:tokens/4 function. The data is tokenized and parsed as if it were a - sequence of Erlang expressions until a final '.' is reached. + sequence of Erlang expressions until a final dot (.) is reached. It returns:

{ok, ExprList, EndLine} @@ -933,7 +932,7 @@ enter>abc("hey". Options argument of the erl_scan:tokens/4 function. The data is tokenized and parsed as if it were an Erlang form - one of the valid Erlang expressions - in an Erlang source file - until a final '.' is reached. It + in an Erlang source file - until a final dot (.) is reached. It returns:

{ok, AbsForm, EndLine} @@ -975,7 +974,7 @@ enter>bar.
Standard Error -

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 standard_error can be used to direct output to whatever the current operating system considers a suitable IO device for error output. Example on a Unix-like operating system:

 $ 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 corresponding io_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 the pid() 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. The io module simply uses the pid() +of the I/O server as the ReplyAs 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. a reference() or something else to differentiate among +the incoming IO replies. The ReplyAs element should be considered +opaque by the I/O server. Note that the pid() of the I/O server is not +explicitly present in the io_reply tuple. The reply can be sent from any +process, not necessarily the actual I/O server. The ReplyAs element is +the only thing that connects one I/O request with an I/O-reply. + +Request and Reply 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 an io_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 Requests exist:

{put_chars, Encoding, Characters}
{put_chars, Encoding, Module, Function, Args}

-Encoding is either 'unicode' or 'latin1', meaning that the +Encoding is either unicode or latin1, 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 to latin1. 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 the Module/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 an iolist(). If Encoding is unicode, 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, and Args denote a function which will be called to + produce the data (like io_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 the Reply 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 Erlang io + 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 Requests 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 Requests exist:

{get_until, Encoding, Prompt, Module, Function, ExtraArgs}

-Encoding denotes how data is to be sent back to the client and +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. If Encoding is latin1, 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; if Encoding is unicode, 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'. + binaries, but the list may contain numbers > 255 if the 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 +

Module, Function, and ExtraArgs 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:

@@ -189,23 +190,23 @@ latin1, Module, Function, Args} respectively.

{done, Result, RestChars}
{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 a list(), the + I/O server may convert it to a binary() 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 case Result is sent to the client and RestChars 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. The Continuation 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 atom eof. An emulation + of the get_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_server

+ apply(Module, Function, [ State, Data | ExtraArgs ]) by the I/O server

-

A 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 and Prompt as for get_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 and Prompt 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 and get_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 the Reply 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 Erlang io + 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 Requests 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 get_line and get_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 the binary option, which allows the Data 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).

+standard Erlang Unicode +format, i.e. UTF-8 (note that the function of the 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 an io: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 to get_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 by proplists (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 and encoding options are common for all +I/O servers in OTP, while echo and expand are valid only for this +I/O server. It is worth noting that the unicode 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 an echo 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} where Option 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 several Requests by using the following format:

{requests, Requests}

-Requests is a list of valid Request tuples for the protocol, they +Requests is a list of valid io_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 atom rows or the atom columns. -

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 actual Request 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.

-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 the reply/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 in io_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 the ReplyAs 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 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.

+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 Encoding directly.

-

When Module, Function and Arguments are provided, we simply apply it +

When Module, Function and Arguments 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 +get_until and using internal helpers to implement get_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:

+we start actually implementing the functions 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 file 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:

+nodes is no longer needed). Note that the I/O server will not work with +a simple 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 function io_reply).

-

The getopt and setopt requests are also simple to handle, we just +

The getopts and setopts 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 +with proplists:substitute_negations/2 and proplists: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 and apply_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 (binary or list) that can be set by +the setopts request. By default, all OTP I/O servers send data back to +the client as lists, but switching mode to binary might increase +efficiency if the I/O 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 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 the get_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 tag unicode, 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 +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 the function did not return a list, the check cannot be performed and the result will be that of the supplied function untouched.

@@ -768,13 +776,13 @@ check(latin1, List) -> end.
-

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 and until_enough/3 are helpers used +together with the get_until/5 function to implement get_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 in get_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 the file +module. It is as simple as that to implement a fully fledged I/O server in Erlang.

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.

-

When the unicode option is given, the regular expression should be given as a valid unicode charlist(), otherwise as any valid iodata().

+

When the unicode option is given, the regular expression should be given as a valid Unicode charlist(), otherwise as any valid iodata().

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 unicode charlist() subject. + The regular expression is given as a Unicode charlist() and the resulting regular expression code is to be run against a valid Unicode charlist() 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. caseless @@ -478,7 +478,7 @@ This option makes it possible to include comments inside complicated patterns. N

Replaces the matched part of the Subject string with the contents of Replacement.

The permissible options are the same as for re:run/3, except that the capture option is not allowed. Instead a {return, ReturnType} is present. The default return type is iodata, constructed in a - way to minimize copying. The iodata result can be used directly in many i/o-operations. If a flat list() is + way to minimize copying. The iodata result can be used directly in many I/O-operations. If a flat list() is desired, specify {return, list} and if a binary is preferred, specify {return, binary}.

As in the re:run/3 function, an mp() 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 -

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.

@@ -48,13 +48,13 @@ -

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 that byte_size(Bin) >= 4. +

Check 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 InEncoding parameter should be given as @@ -148,18 +150,18 @@

If InEncoding is latin1, the Data parameter corresponds to the iodata() type, but for unicode, the Data parameter 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 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 for utf8, as this is the +

The option unicode is an alias for utf8, as this is the preferred encoding for Unicode characters in binaries. utf16 is an alias for {utf16,big} and utf32 is an alias for {utf32,big}. The big @@ -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 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.

+ list and whatever is left to decode is simply returned as is.

However, if the input Data 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 greater than 16#10FFFF - (the maximum unicode character), + (the maximum Unicode character), in the range 16#D800 to 16#DFFF (invalid range reserved for UTF-16 surrogate pairs) @@ -205,14 +207,14 @@ (like the upper bits of the bytes being wrong), the bytes are decoded to a too large number, the bytes are decoded to a code-point in the - invalid unicode - range or encoding is "overlong", meaning that a + invalid Unicode + range, or encoding is "overlong", meaning that a number should have been encoded in fewer bytes. The case of a truncated UTF is handled specially, see the paragraph about incomplete binaries below. If InEncoding is latin1, binaries are always valid as long as they contain whole bytes, - as each byte falls into the valid iso-latin-1 range. + as each byte falls into the valid ISO-latin-1 range. @@ -250,7 +252,7 @@ ever be decoded.

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 badarg exception is thrown.

@@ -258,28 +260,27 @@
- Convert a collection of characters to an UTF-8 binary + Convert a collection of characters to a UTF-8 binary -

Same as characters_to_binary(Data, unicode, unicode).

+

Same as characters_to_binary(Data, unicode, unicode).

- Convert a collection of characters to an UTF-8 binary + Convert a collection of characters to a UTF-8 binary -

Same as characters_to_binary(Data, InEncoding, unicode).

+

Same as characters_to_binary(Data, InEncoding, unicode).

- Convert a collection of characters to an UTF-8 binary + Convert a collection of characters to a UTF-8 binary -

This function behaves as - characters_to_list/2, but produces an binary - instead of a unicode list. The +

Behaves as + characters_to_list/2, but produces an binary + instead of a Unicode list. The InEncoding defines how input is to be interpreted if binaries are present in the Data, while OutEncoding defines in what format output is to be @@ -294,7 +295,7 @@

Errors and exceptions occur as in - characters_to_list/2, but the second element + characters_to_list/2, but the second element in the error or incomplete tuple will be a binary() and not a list().

@@ -304,16 +305,18 @@ Create a binary UTF byte order mark from encoding. - A binary() of byte_size 4 or more. + + A binary() such that byte_size(Bin) >= 4. + -

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 InEncoding. The BOM is, if supported at all, expected to be placed first in UTF encoded files or messages.

The function returns <<>> for the - latin1 encoding, there is no BOM for ISO-latin-1.

+ latin1 encoding as there is no BOM for ISO-latin-1.

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 @@ unicode_usage.xml

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.

-What Unicode is +What Unicode Is

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.

-Standard Unicode representation in Erlang +Standard Unicode Representation in Erlang

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 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.

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 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:

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 unicode in STDLIB even supports similar mixes with binaries containing other encodings than UTF-8, but that is a special case to allow for conversions to and from external data:

-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
-Basic language support for Unicode +Basic Language Support for Unicode

As of Erlang/OTP R16 Erlang can be written in ISO-latin-1 or Unicode (UTF-8). The details on how to state the encoding of an Erlang source file can be found in

-String- and character-literals -

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 +String- and Character-literals +

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 number of hexadecimal digits and a terminating right curly bracket). This allows for entering characters of any codepoint literally in a string even when the encoding is ISO-latin-1.

-

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, $ can be followed directly by a Unicode character producing an integer. In the following example the codepoint of a Cyrillic s is output:

 7> $с.
 1089
-The interactive shell +The Interactive Shell

The interactive Erlang shell, when started towards a terminal or started using the werl command on windows, can support Unicode input and output.

-

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 (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:

 $ 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 LC_CTYPE variable before LANG, so if that is set, it has to be set to UTF-8:

 $ 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 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.

To investigate what Erlang thinks about the terminal, the io:getopts() call can be used when the shell is started:

 $ 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> 
-Unicode file names +Unicode File Names

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:

Mandatory Unicode file naming @@ -189,7 +197,7 @@ Eshell V5.10 (abort with ^G)

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 encoding options given when opening a file has nothing to do with the file name encoding convention. You can very well open files containing UTF-8 but having file names in ISO-latin-1 or vice versa.

-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. +

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.

-Notes about raw file names and automatic file name conversion +Notes About Raw File Names and Automatic File Name Conversion

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 file:list_dir/1 is a good idea. But what would happen if we later tried to open the file and have the name as a Unicode list (magically converted from the ISO-latin-1 file name)? The VM will convert the file name given to UTF-8, as this is the encoding expected. Effectively this means trying to open the file named <<"björn"/utf8>>. This file does not exist, and even if it existed it would not be the same file as the one that was listed. We could even create two files named "björn", one named in the UTF-8 encoding and one not. If file:list_dir/1 would automatically convert the ISO-latin-1 file name to a list, we would get two identical file names as the result. To avoid this, we need to differentiate between file names being properly encoded according to the Unicode file naming convention (i.e. UTF-8) and file names being invalid under the encoding. This is done by representing invalid encoding as "raw" file names, i.e. as binaries.

The core system of Erlang (Kernel and STDLIB) accepts raw file names except for loadable drivers and executables invoked using open_port({spawn, ...} ...). open_port({spawn_executable, ...} ...) however does accept them. As mentioned earlier, the arguments given in the option list to open_port({spawn_executable, ...} ...) undergo the same conversion as the file names, meaning that the executable will be provided with arguments in UTF-8 as well. This translation is avoided consistently with how the file names are treated, by giving the argument as a binary.

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 file:native_name_encoding/0 function, which returns either the atom latin1 or the atom utf8 depending on the file name translation mode. On Linux, a VM started without explicitly stating the file name translation mode will default to latin1 as the native file name encoding, why file names on the disk encoded as UTF-8 will be returned as a list of the names interpreted as ISO-latin-1. The "UTF-8 list" is not a practical type for displaying or operating on in Erlang, but it is backward compatible and usable in all functions requiring a file name. On Windows and MacOSX, the default behavior is that of file name translation, why the file:native_name_encoding/0 by default returns utf8 on those systems (the fact that Windows actually does not use UTF-8 on the file system level can safely be ignored by the Erlang programmer). The default behavior can be changed using the +fnu or +fnl options to the VM, see the erl command manual page.

+

If working with raw file names, one can still conform to the encoding convention of the Erlang VM by using the file:native_name_encoding/0 function, which returns either the atom latin1 or the atom utf8 depending on the file name translation mode. On Linux, a VM started without explicitly stating the file name translation mode will default to latin1 as the native file name encoding, why file names on the disk encoded as UTF-8 will be returned as a list of the names interpreted as ISO-latin-1. The "UTF-8 list" is not a practical type for displaying or operating on in Erlang, but it is backward compatible and usable in all functions requiring a file name. On Windows and MacOSX, the default behavior is that of file name translation, why the file:native_name_encoding/0 by default returns utf8 on those systems (the fact that Windows actually does not use UTF-8 on the file system level can safely be ignored by the Erlang programmer). The default behavior can be changed using the +fnu or +fnl options to the VM, see the erl(1) command manual page.

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.

-Notes about MacOSX +Notes About MacOSX

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 +fnl flag or to use a raw file name in latin1 encoding. In that case, the file can not be opened with the same name as the one used to create this. The problem is by design in newer versions of MacOSX.

MacOSX also reorganizes the names of files so that the representation of accents etc is denormalized, i.e. the character ö is represented as the codepoints [111,776], where 111 is the character o and 776 is a special accent character. This type of denormalized Unicode is otherwise very seldom used and Erlang normalizes those file names on retrieval, so that denormalized file names is not passed up to the Erlang application. In Erlang the file name "björn" is retrieved as [98,106,246,114,110], not as [98,106,117,776,114,110], even though the file system might think differently.

-Unicode in environment variables and parameters +Unicode in Environment Variables and Parameters

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 os:getenv/0, os:getenv/1 and os:putenv/2 will handle Unicode strings. On Unix-like platforms, the built-in functions will translate environment variables in UTF-8 to/from Unicode strings, possibly with codepoints > 255. On Windows the Unicode versions of the environment system API will be used, also allowing for codepoints > 255.

On Unix-like operating systems, parameters are expected to be UTF-8 without translation if Unicode file names are enabled.

-Unicode-aware modules -

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 gen_tcp etc).

+Unicode-aware Modules +

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 gen_tcp etc).

Modules that actually handle textual data (like io_lib, string etc) are sometimes subject to conversion or extension to be able to handle Unicode characters.

Fortunately, most textual data has been stored in lists and range checking has been sparse, why modules like string works well for Unicode lists with little need for conversion or extension.

Some modules are however changed to be explicitly Unicode-aware. These modules include:

@@ -237,7 +245,7 @@ Eshell V5.10 (abort with ^G)

The io module has been extended along with the actual I/O-protocol to handle Unicode data. This means that several functions require binaries to be in UTF-8 and there are modifiers to formatting control sequences to allow for outputting of Unicode strings.

-file, group and user +file, group, user

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 shell has support for Unicode terminals and the file module allows for translation to and from various Unicode formats on disk.

The actual reading and writing of files with Unicode data is however not best done with the file module as its interface is byte oriented. A file opened with a Unicode encoding (like UTF-8), is then best read or written using the io module.

@@ -254,10 +262,10 @@ Eshell V5.10 (abort with ^G)

The module string works perfect for Unicode strings as well as for ISO-latin-1 strings with the exception of the language-dependent to_upper and to_lower functions, which are only correct for the ISO-latin-1 character set. Actually they can never function correctly for Unicode characters in their current form, there are language and locale issues as well as multi-character mappings to consider when conversion text between cases. Converting case in an international environment is a big subject not yet addressed in OTP.

-Unicode recipes +Unicode Recipes

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.

-Byte order marks +Byte Order Marks

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 io module). Note that error handling is omitted from the code:

open_bom_file_for_reading(File) -> @@ -268,7 +276,7 @@ open_bom_file_for_reading(File) -> io:setopts(F,[{encoding,Type}]), {ok,F}. -

The unicode:bom_to_encoding/1 function identifies the encoding from a binary of at least four bytes. It returns, along with an term suitable for setting the encoding of the file, the actual length of the BOM, so that the file position can be set accordingly. Note that file:position always works on byte-offsets, so that the actual byte-length of the BOM is needed.

+

The unicode:bom_to_encoding/1 function identifies the encoding from a binary of at least four bytes. It returns, along with an term suitable for setting the encoding of the file, the actual length of the BOM, so that the file position can be set accordingly. Note that file:position/2 always works on byte-offsets, so that the actual byte-length of the BOM is needed.

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.

-Formatted input and output -

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 io or io_lib. For backward compatibility reasons, these functions don't accept just any list as a string, but require e special "translation modifier" when working with Unicode texts. The modifier is "t". When applied to the "s" control character in a formatting string, it accepts all Unicode codepoints and expect binaries to be in UTF-8:

+Formatted Input and Output +

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 io or io_lib. For backward compatibility reasons, these functions do not accept just any list as a string, but require a special translation modifier when working with Unicode texts. The modifier is t. When applied to the s control character in a formatting string, it accepts all Unicode codepoints and expect binaries to be in UTF-8:

 1> io:format("~ts~n",[<<"åäö"/utf8>>]).
 åäö
@@ -289,21 +297,24 @@ ok
 2> io:format("~s~n",[<<"åäö"/utf8>>]).
 åäö
 ok
-

Obviously the second io:format gives undesired output because the UTF-8 binary is not in latin1. Because ISO-latin-1 is still the defined character set of Erlang, the non prefixed "s" control character expects ISO-latin-1 in binaries as well as lists.

-

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 format in io_lib behaves similarly. This function is defined to return a deep list of characters and the output could easily be converted to binary data for outputting on a device of any kind by a simple erlang:list_to_binary. When the translation modifier is used, the list can however contain characters that cannot be stored in one byte. The call to erlang:list_to_binary will in that case fail. However, if the io_server you want to communicate with is Unicode-aware, the list returned can still be used directly:

+

Obviously the second io:format/2 gives undesired output because the UTF-8 binary is not in latin1. Because ISO-latin-1 is still the defined character set of Erlang, the non prefixed s control character expects ISO-latin-1 in binaries as well as lists.

+

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 right choice of formatting characters.

+

The function format/2 in io_lib behaves similarly. This function is defined to return a deep list of characters and the output could easily be converted to binary data for outputting on a device of any kind by a simple erlang:list_to_binary/1. When the translation modifier is used, the list can however contain characters that cannot be stored in one byte. The call to erlang:list_to_binary/1 will in that case fail. However, if the I/O server you want to communicate with is Unicode-aware, the list returned can still be used directly:

+$ 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 io:put_chars function, so data can be output on any Unicode capable device. If the device is a terminal, characters will be output in the \x{H ...} format if encoding is latin1 otherwise in UTF-8 (for the non-interactive terminal - "oldshell" or "noshell") or whatever is suitable to show the character properly (for an interactive terminal - the regular shell). The bottom line is that you can always send Unicode data to the standard_io device. Files will however only accept Unicode codepoints beyond ISO-latin-1 if encoding is set to something else than latin1.

+

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 io:put_chars/2 function, so data can be output on any Unicode capable device. If the device is a terminal, characters will be output in the \x{H ...} format if encoding is latin1 otherwise in UTF-8 (for the non-interactive terminal - "oldshell" or "noshell") or whatever is suitable to show the character properly (for an interactive terminal - the regular shell). The bottom line is that you can always send Unicode data to the standard_io device. Files will however only accept Unicode codepoints beyond ISO-latin-1 if encoding is set to something else than latin1.

-Heuristic identification of UTF-8 -

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.

+Heuristic Identification of UTF-8 +

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 unicode module can be used to determine if data can be interpreted as UTF-8:

heuristic_encoding_bin(Bin) when is_binary(Bin) -> -- cgit v1.2.3