common.h File Reference

Prototypes for various functions, mostly string utilities, that are used by most parts of fish. More...

#include <stdlib.h>
#include <stdio.h>
#include <wchar.h>
#include <termios.h>
#include "util.h"

This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Defines

#define MAX_UTF8_BYTES   6
 Header guard.
#define ENCODE_DIRECT_BASE   0xf100
 This is in the unicode private use area.
#define ASCII_MAX   127u
 Highest legal ascii value.
#define UCS2_MAX   0xffffu
 Highest legal 16-bit unicode value.
#define BYTE_MAX   0xffu
 Highest legal byte value.
#define UNESCAPE_SPECIAL   1
 Escape special fish syntax characters like the semicolon.
#define UNESCAPE_INCOMPLETE   2
 Allow incomplete escape sequences.
#define ESCAPE_ALL   1
 Escape all characters, including magic characters like the semicolon.
#define ESCAPE_NO_QUOTED   2
 Do not try to use 'simplified' quoted escapes, and do not use empty quotes as the empty string.
#define CHECK(arg, retval)
 This macro is used to check that an input argument is not null.
#define FATAL_EXIT()
 Pause for input, then exit the program.
#define DIE_MEM()
 Exit program at once, leaving an error message about running out of memory.
#define CHECK_BLOCK(retval)
 Check if signals are blocked.
#define _(wstr)   wgettext(wstr)
 Shorthand for wgettext call.
#define N_(wstr)   wstr
 Noop, used to tell xgettext that a string should be translated, even though it is not directly sent to wgettext.
#define contains(str,...)   contains_internal( str, __VA_ARGS__, (void *)0 )
 Check if the specified stringelement is a part of the specified string list.
#define wcsdupcat(str,...)   wcsdupcat_internal( str, __VA_ARGS__, (void *)0 )
 Concatenate all the specified strings into a single newly allocated one.

Functions

void show_stackframe ()
 Print a stack trace to stderr.
wchar_t ** list_to_char_arr (array_list_t *l)
 Take an array_list_t containing wide strings and converts them to a single null-terminated wchar_t **.
int fgetws2 (wchar_t **buff, int *len, FILE *f)
 Read a line from the stream f into the buffer buff of length len.
void sort_list (array_list_t *comp)
 Sorts an array_list of wide strings according to the wcsfilecmp-function from the util library.
wchar_t * str2wcs (const char *in)
 Returns a newly allocated wide character string equivalent of the specified multibyte character string.
wchar_t * str2wcs_internal (const char *in, wchar_t *out)
 Converts the narrow character string in into it's wide equivalent, stored in out.
char * wcs2str (const wchar_t *in)
 Returns a newly allocated multibyte character string equivalent of the specified wide character string.
char * wcs2str_internal (const wchar_t *in, char *out)
 Converts the wide character string in into it's narrow equivalent, stored in out.
char ** wcsv2strv (const wchar_t **in)
 Returns a newly allocated wide character string array equivalent of the specified multibyte character string array.
wchar_t ** strv2wcsv (const char **in)
 Returns a newly allocated multibyte character string array equivalent of the specified wide character string array.
__sentinel wchar_t * wcsdupcat_internal (const wchar_t *a,...)
 Returns a newly allocated concatenation of the specified wide character strings.
wchar_t * wcsvarname (const wchar_t *str)
 Test if the given string is a valid variable name.
wchar_t * wcsfuncname (const wchar_t *str)
 Test if the given string is a valid function name.
int wcsvarchr (wchar_t chr)
 Test if the given string is valid in a variable name.
int my_wcswidth (const wchar_t *c)
 A wcswidth workalike.
wchar_t * quote_end (const wchar_t *in)
 This functions returns the end of the quoted substring beginning at in.
void error_reset ()
 A call to this function will reset the error counter.
const wchar_t * wsetlocale (int category, const wchar_t *locale)
 This function behaves exactly like a wide character equivalent of the C function setlocale, except that it will also try to detect if the user is using a Unicode character set, and if so, use the unicode ellipsis character as ellipsis, instead of '$'.
__sentinel int contains_internal (const wchar_t *needle,...)
 Checks if needle is included in the list of strings specified.
int read_blocked (int fd, void *buf, size_t count)
 Call read while blocking the SIGCHLD signal.
ssize_t write_loop (int fd, char *buff, size_t count)
 Loop a write request while failiure is non-critical.
void debug (int level, const wchar_t *msg,...)
 Issue a debug message with printf-style string formating and automatic line breaking.
wchar_t * escape (const wchar_t *in, int escape_all)
 Replace special characters with backslash escape sequences.
wchar_t * unescape (const wchar_t *in, int escape_special)
 Expand backslashed escapes and substitute them with their unescaped counterparts.
int acquire_lock_file (const char *lockfile, const int timeout, int force)
 Attempt to acquire a lock based on a lockfile, waiting LOCKPOLLINTERVAL milliseconds between polls and timing out after timeout seconds, thereafter forcibly attempting to obtain the lock if force is non-zero.
int common_get_width ()
 Returns the width of the terminal window, so that not all functions that use these values continually have to keep track of it separately.
int common_get_height ()
 Returns the height of the terminal window, so that not all functions that use these values continually have to keep track of it separatly.
void common_handle_winch (int signal)
 Handle a window change event by looking up the new window size and saving it in an internal variable used by common_get_wisth and common_get_height().
void write_screen (const wchar_t *msg, string_buffer_t *buff)
 Write paragraph of output to the specified stringbuffer, and redo the linebreaks to fit the current screen.
void tokenize_variable_array (const wchar_t *val, array_list_t *out)
 Tokenize the specified string into the specified array_list_t.
int create_directory (wchar_t *d)
 Make sure the specified direcotry exists.
void bugreport ()
 Print a short message about how to file a bug report to stderr.
void sb_format_size (string_buffer_t *sb, long long sz)
 Format the specified size (in bytes, kilobytes, etc.
double timef ()
 Return the number of seconds from the UNIX epoch, with subsecond precision.

Variables

struct termios shell_modes
 Save the shell mode on startup so we can restore them on exit.
wchar_t ellipsis_char
 The character to use where the text has been truncated.
int debug_level
 The verbosity level of fish.
char * profile
 Profiling flag.
wchar_t * program_name
 Name of the current program.


Detailed Description

Prototypes for various functions, mostly string utilities, that are used by most parts of fish.


Define Documentation

#define CHECK ( arg,
retval   ) 

Value:

if( !(arg) )                                                                                                            \
        {                                                                                                                                       \
                debug( 0,                                                                                                               \
                           _( L"function %s called with null value for argument %s. " ), \
                           __func__,                                                                                            \
                           #arg );                                                                                                      \
                bugreport();                                                                                                    \
                show_stackframe();                                                                                              \
                return retval;                                                                                                  \
        }
This macro is used to check that an input argument is not null.

It is a bit lika a non-fatal form of assert. Instead of exit-ing on failiure, the current function is ended at once. The second parameter is the return value of the current function on failiure.

Referenced by al_contains_str(), al_empty(), al_foreach(), al_foreach2(), al_get_count(), al_truncate(), b_append(), b_destroy(), b_init(), builtin_exists(), builtin_get_desc(), builtin_get_names(), builtin_run(), complete(), complete_add(), complete_is_valid_option(), complete_load(), complete_print(), complete_remove(), complete_set_authoritative(), contains_internal(), debug(), env_exist(), env_get(), env_get_names(), env_remove(), env_set(), env_universal_common_set(), env_universal_get(), env_universal_get_export(), env_universal_get_names(), env_universal_remove(), env_universal_set(), error(), eval_args(), event_add_handler(), event_free(), event_get(), event_get_desc(), event_remove(), exec(), exec_subshell(), expand_brackets(), expand_cmdsubst(), expand_escape_variable(), expand_is_clean(), expand_one(), expand_pid(), expand_string(), expand_tilde(), expand_tilde_internal(), expand_variables(), file_get_desc(), function_add(), function_exists(), function_get_definition(), function_get_definition_file(), function_get_definition_offset(), function_get_desc(), function_get_named_arguments(), function_get_names(), function_get_shadows(), function_remove(), function_set_desc(), highlight_shell(), input_function_get_names(), input_mapping_add(), input_terminfo_get_name(), input_terminfo_get_names(), input_terminfo_get_sequence(), internal_help(), job_or_process_extent(), output_set_writer(), parse_util_cmdsubst_extent(), parse_util_lineno(), parse_util_load(), parse_util_load_reset(), parse_util_locate_cmdsubst(), parse_util_token_extent(), parse_util_unescape_wildcards(), parse_util_unload(), parser_find_end(), parser_forbid_function(), parser_is_help(), parser_stack_trace(), parser_test(), parser_test_args(), parser_test_argument(), path_get_path(), print_errors(), printed_width(), reader_can_replace(), remove_internal_separator(), s_destroy(), s_init(), s_reset(), s_write(), sb_append_char(), sb_append_internal(), sb_append_substring(), sb_destroy(), sb_init(), sb_length(), sb_printf(), sb_truncate(), sb_vprintf(), str2wcs_internal(), tok_destroy(), tok_first(), tok_get_pos(), tok_has_next(), tok_init(), tok_last(), tok_last_quote(), tok_last_type(), tok_next(), tok_set_pos(), unescape(), wcs2str_internal(), wcsfilecmp(), wildcard_completion_allocate(), write_escaped_str(), write_screen(), writembs_internal(), writestr(), and writestr_ellipsis().

#define CHECK_BLOCK ( retval   ) 

Value:

if( signal_is_blocked() )                                                                                       \
        {                                                                                                                                       \
                debug( 0,                                                                                                               \
                           _( L"function %s called while blocking signals. " ),         \
                           __func__);                                                                                           \
                bugreport();                                                                                                    \
                show_stackframe();                                                                                              \
                return retval;                                                                                                  \
        }
Check if signals are blocked.

If so, print an error message and return from the function performing this check.

Referenced by eval(), exec(), input_readch(), job_continue(), and parse_util_load().

 
#define DIE_MEM (  ) 

 
#define FATAL_EXIT (  ) 

Value:

{                                                                                                                       \
                int exit_read_count;char exit_read_buff;                                \
                show_stackframe();                                                                              \
                exit_read_count=read( 0, &exit_read_buff, 1 );                  \
                exit( 1 );                                                                                              \
        }                                                                                                                       \
Pause for input, then exit the program.

If supported, print a backtrace first.

Referenced by escape(), eval(), exec_fork(), free_fd(), signal_set_handlers(), and signal_unblock().

#define MAX_UTF8_BYTES   6

Header guard.

Maximum number of bytes used by a single utf-8 character

Referenced by wcs2str(), wcs2utf(), wgetcwd(), wgettext_wcs2str(), and wutil_wcs2str().


Function Documentation

int acquire_lock_file ( const char *  lockfile,
const int  timeout,
int  force 
)

Attempt to acquire a lock based on a lockfile, waiting LOCKPOLLINTERVAL milliseconds between polls and timing out after timeout seconds, thereafter forcibly attempting to obtain the lock if force is non-zero.

Returns 1 on success, 0 on failure. To release the lock the lockfile must be unlinked. A unique temporary file named by appending characters to the lockfile name is used; any pre-existing file of the same name is subject to deletion.

References debug(), gen_unique_nfs_filename(), and LOCKPOLLINTERVAL.

Referenced by acquire_socket_lock().

int common_get_height (  ) 

Returns the height of the terminal window, so that not all functions that use these values continually have to keep track of it separatly.

Only works if common_handle_winch is registered to handle winch signals.

References termsize, and winsize::ws_row.

Referenced by builtin_print_help(), and env_get().

int common_get_width (  ) 

Returns the width of the terminal window, so that not all functions that use these values continually have to keep track of it separately.

Only works if common_handle_winch is registered to handle winch signals.

References termsize, and winsize::ws_col.

Referenced by builtin_function(), env_get(), s_desired_append_char(), s_update(), s_write(), and write_screen().

__sentinel int contains_internal ( const wchar_t *  needle,
  ... 
)

Checks if needle is included in the list of strings specified.

A warning is printed if needle is zero.

Parameters:
needle the string to search for in the list
Returns:
zero if needle is not found, of if needle is null, non-zero otherwise

References CHECK.

int create_directory ( wchar_t *  d  ) 

Make sure the specified direcotry exists.

If needed, try to create it and any currently not existing parent directories..

Returns:
0 if, at the time of function return the directory exists, -1 otherwise.

References create_directory(), wdirname(), wmkdir(), and wstat().

Referenced by create_directory(), fishd_get_config(), and path_get_config().

void debug ( int  level,
const wchar_t *  msg,
  ... 
)

Issue a debug message with printf-style string formating and automatic line breaking.

The string will begin with the string program_name, followed by a colon and a whitespace.

Because debug is often called to tell the user about an error, before using wperror to give a specific error message, debug will never ever modify the value of errno.

Parameters:
level the priority of the message. Lower number means higher priority. Messages with a priority_number higher than debug_level will be ignored..
msg the message format string.
Example:

debug( 1, L"Pi = %.3f", M_PI );

will print the string 'fish: Pi = 3.141', given that debug_level is 1 or higher, and that program_name is 'fish'.

References buffer::buff, CHECK, debug_level, program_name, sb_destroy(), sb_init(), sb_printf(), sb_vprintf(), and write_screen().

Referenced by acquire_lock_file(), bugreport(), builtin_end(), builtin_run(), clear_value(), close_unused_internal_pipes(), complete_param_expand(), create_message(), daemonize(), do_builtin_io(), env_export_arr(), env_pop(), env_universal_read_all(), env_universal_remove(), env_universal_set(), escape(), eval(), event_fire_delayed(), exec(), exec_close(), exec_fork(), exec_pipe(), exec_subshell(), expand_string(), fish_parse_opt(), fishd_get_config(), free_fd(), gen_unique_nfs_filename(), get_socket(), get_socket_filename(), handle_child_io(), handle_locale(), history_save_mode(), indent(), input_common_readch(), input_destroy(), input_init(), io_buffer_create(), io_buffer_read(), io_print(), io_transmogrify(), job_continue(), job_remove(), kill_sanity_check(), launch_process(), load_or_save(), main(), parse_job(), parse_job_argument_list(), parse_message(), parse_util_load(), parser_destroy(), parser_pop_block(), path_get_config(), path_get_path(), print_errors_stderr(), proc_destroy(), proc_sanity_check(), read_message(), read_ni(), read_try(), readb(), reader_interactive_init(), reader_pop(), reader_readline(), run_pager(), sanity_lose(), select_try(), set_child_group(), setup_path(), show_stackframe(), signal_unblock(), start_fishd(), term_donate(), term_steal(), terminal_give_to_job(), terminal_return_from_job(), try_send(), try_send_all(), utf2wcs(), validate_pointer(), wcs2str_internal(), wcs2utf(), wildcard_complete_internal(), wildcard_expand_internal(), wildcard_has(), writestr(), and wutil_destroy().

void error_reset (  ) 

A call to this function will reset the error counter.

Some functions print out non-critical error messages. These should check the error_count before, and skip printing the message if MAX_ERROR_COUNT messages have been printed. The error_reset() should be called after each interactive command executes, to allow new messages to be printed.

wchar_t* escape ( const wchar_t *  in,
int  escape_all 
)

Replace special characters with backslash escape sequences.

Newline is replaced with
, etc.

Parameters:
in The string to be escaped
escape_all Whether all characters wich hold special meaning in fish (Pipe, semicolon, etc,) should be escaped, or only unprintable characters
Returns:
The escaped string, or 0 if there is not enough memory

References debug(), DIE_MEM, ENCODE_DIRECT_BASE, ESCAPE_ALL, ESCAPE_NO_QUOTED, escape_simple(), FATAL_EXIT, out, and tmp.

Referenced by append_switch(), builtin_bind_list(), builtin_help_get(), complete_cmd_desc(), complete_get_desc_suffix(), completion_insert(), event_fire_internal(), expand_cmdsubst(), expand_escape_variable(), functions_def(), kill_add(), kill_check_x_buffer(), parse_util_load_internal(), print_variables(), read_init(), run_pager(), test_escape(), and write_escaped_str().

int fgetws2 ( wchar_t **  buff,
int *  len,
FILE *  f 
)

Read a line from the stream f into the buffer buff of length len.

If buff is to small, it will be reallocated, and both buff and len will be updated to reflect this. Returns the number of bytes read or -1 on failiure.

If the carriage return character is encountered, it is ignored. fgetws() considers the line to end if reading the file results in either a newline (L'
') character, the null (L'\0') character or the end of file (WEOF) character.

References buff, DIE_MEM, and maxi().

Referenced by find_process().

wchar_t** list_to_char_arr ( array_list_t l  ) 

Take an array_list_t containing wide strings and converts them to a single null-terminated wchar_t **.

The array is allocated using malloc, and needs to be fred's by the caller.

References al_get(), al_get_count(), and DIE_MEM.

Referenced by parse_job(), and parse_job_argument_list().

int my_wcswidth ( const wchar_t *  c  ) 

A wcswidth workalike.

Fish uses this since the regular wcswidth seems flaky.

A wcswidth workalike.

fish uses this replacement.

Referenced by parser_current_line(), print_all(), write_escaped_str(), and writestr_ellipsis().

wchar_t* quote_end ( const wchar_t *  in  ) 

This functions returns the end of the quoted substring beginning at in.

The type of quoting character is detemrined by examining in. Returns 0 on error.

Parameters:
in the position of the opening quote

Referenced by get_quote(), parse_util_locate_cmdsubst(), and read_string().

int read_blocked ( int  fd,
void *  buf,
size_t  count 
)

Call read while blocking the SIGCHLD signal.

Should only be called if you _know_ there is data available for reading, or the program will hang until there is data.

Referenced by builtin_read(), io_buffer_read(), read_try(), and readb().

void sb_format_size ( string_buffer_t sb,
long long  sz 
)

Format the specified size (in bytes, kilobytes, etc.

) into the specified stringbuffer.

References _, sb_append, and sb_printf().

Referenced by launch_process(), and wildcard_completion_allocate().

wchar_t* str2wcs ( const char *  in  ) 

Returns a newly allocated wide character string equivalent of the specified multibyte character string.

This function encodes illegal character sequences in a reversible way using the private use area.

References DIE_MEM, out, and str2wcs_internal().

Referenced by builtin_wperror(), env_init(), env_set_defaults(), exec_subshell(), expand_tilde_internal(), find_process(), fishd_env_get(), main(), read_ni(), run_pager(), strv2wcsv(), test_convert(), try_complete_user(), and wrealpath().

wchar_t* str2wcs_internal ( const char *  in,
wchar_t *  out 
)

Converts the narrow character string in into it's wide equivalent, stored in out.

out must have enough space to fit the entire string.

This function encodes illegal character sequences in a reversible way using the private use area.

References CHECK, ENCODE_DIRECT_BASE, and INTERNAL_SEPARATOR.

Referenced by str2wcs(), and wutil_str2wcs().

double timef (  ) 

Return the number of seconds from the UNIX epoch, with subsecond precision.

This function uses the gettimeofday function, and will have the same precision as that function.

If an error occurs, NAN is returned.

Referenced by try_complete_user().

void tokenize_variable_array ( const wchar_t *  val,
array_list_t out 
)

Tokenize the specified string into the specified array_list_t.

Each new element is allocated using malloc and must be freed by the caller.

Parameters:
val the input string. The contents of this string is not changed.
out the list in which to place the elements.

References al_push(), ARRAY_SEP, and DIE_MEM.

Referenced by autoload_names(), builtin_set(), expand_escape_variable(), expand_variables(), output_color_code(), parse_util_load(), and setup_path().

wchar_t* unescape ( const wchar_t *  in,
int  escape_special 
)

Expand backslashed escapes and substitute them with their unescaped counterparts.

Also optionally change the wildcards, the tilde character and a few more into constants which are defined in a private use area of Unicode. This assumes wchar_t is a unicode character set.

The result must be free()d. The original string is not modified. If an invalid sequence is specified, 0 is returned.

References ANY_CHAR, ANY_STRING, ANY_STRING_RECURSIVE, ASCII_MAX, BRACKET_BEGIN, BRACKET_END, BRACKET_SEP, BYTE_MAX, CHECK, DIE_MEM, ENCODE_DIRECT_BASE, HOME_DIRECTORY, INTERNAL_SEPARATOR, PROCESS_EXPAND, UCS2_MAX, UNESCAPE_INCOMPLETE, UNESCAPE_SPECIAL, VARIABLE_EXPAND, and VARIABLE_EXPAND_SINGLE.

Referenced by builtin_complete(), complete(), expand_unescape(), indent(), is_potential_path(), parse_message(), parser_test_argument(), test_escape(), and write_part().

char* wcs2str ( const wchar_t *  in  ) 

Returns a newly allocated multibyte character string equivalent of the specified wide character string.

This function decodes illegal character sequences in a reversible way using the private use area.

References DIE_MEM, MAX_UTF8_BYTES, out, and wcs2str_internal().

Referenced by env_set_defaults(), exec(), expand_tilde_internal(), export_func2(), fishd_env_get(), launch_process(), load_or_save(), run_pager(), s_write(), test_convert(), wcsv2strv(), wildcard_expand_internal(), wrename(), and wsetlocale().

char* wcs2str_internal ( const wchar_t *  in,
char *  out 
)

Converts the wide character string in into it's narrow equivalent, stored in out.

out must have enough space to fit the entire string.

This function decodes illegal character sequences in a reversible way using the private use area.

References CHECK, debug(), ENCODE_DIRECT_BASE, and INTERNAL_SEPARATOR.

Referenced by wcs2str(), wgettext_wcs2str(), and wutil_wcs2str().

__sentinel wchar_t* wcsdupcat_internal ( const wchar_t *  a,
  ... 
)

Returns a newly allocated concatenation of the specified wide character strings.

The last argument must be a null pointer.

References DIE_MEM.

wchar_t* wcsfuncname ( const wchar_t *  str  ) 

Test if the given string is a valid function name.

Returns:
null if this is a valid name, and a pointer to the first invalid character otherwise

Referenced by builtin_function().

int wcsvarchr ( wchar_t  chr  ) 

Test if the given string is valid in a variable name.

Returns:
1 if this is a valid name, 0 otherwise

Referenced by highlight_param(), and parser_test_argument().

wchar_t* wcsvarname ( const wchar_t *  str  ) 

Test if the given string is a valid variable name.

Test if the given string is a valid variable name.

Returns:
null if this is a valid name, and a pointer to the first invalid character otherwise

Referenced by builtin_for(), builtin_function(), builtin_set(), create_message(), expand_variable_error(), and parser_test().

ssize_t write_loop ( int  fd,
char *  buff,
size_t  count 
)

Loop a write request while failiure is non-critical.

Return -1 and set errno in case of critical error.

References out.

Referenced by handle_completions(), load_or_save(), reader_readline(), s_check_status(), s_reset(), s_update(), s_write(), and writeb_internal().


Variable Documentation

The verbosity level of fish.

If a call to debug has a severity level higher than debug_level, it will not be printed.

Referenced by debug(), fish_parse_opt(), read_message(), and try_send().

wchar_t ellipsis_char

The character to use where the text has been truncated.

Is an ellipsis on unicode system and a $ on other systems.

Referenced by handle_completions(), s_desired_append_char(), write_escaped_str(), writestr_ellipsis(), and wsetlocale().

char* profile

Profiling flag.

True if commands should be profiled.

Referenced by eval_job(), fish_parse_opt(), parser_destroy(), and parser_init().

wchar_t* program_name

Name of the current program.

Should be set at startup. Used by the debug function.

Referenced by debug(), job_reap(), main(), and reader_run_command().


Generated on Sun Mar 8 15:46:54 2009 for fish by  doxygen 1.5.6