Functions

Function list

You can use the following functions in the macro sequence:

Математические функции
Function Description
N=abs(N) Returns the absolute value of a numeric argument N.
N=max(N1,N2) Returns the maximal value of two numeric arguments N1 and N2.
N=min(N1,N2) Returns the minimal value of two numeric arguments N1 and N2.
N=mod(N1,N2) Division of N1 by the modulus N2.
N=int(V) Evaluates the V argument to a number.
Строковые функции
Function Description
N=index(S1,S2) Returns the position of the first occurrence of the substring S2 within string S1, -1 otherwise.
N=rindex(S1,S2) Returns the position of the last occurrence of the substring S2 within string S1, -1 otherwise.
Result=replace(Str,Find,Replace[,Cnt]) Replace substing Find in Str with Replace, Cnt times (set Cnt to 0 or omit this parameter to replace all occurrences).
Returns the resulting string.
N=asc(S) Returns the code of character S.
S=chr(N) Returns the character for the code N.
S=itoa(N[,Radix]) Converts numeric value N to a string. Parameter Radix defines the base of the numerical representation for the number conversion. The Radix parameter can be from 2 to 36. If Radix is omitted, base 10 is implied.
N=len(V) Returns the length of the expression V. This function evaluates the value of V to a string and then returns the length of the string.
S=string(V) Converts the value of the expression V to a string.
S=substr(V,N1[,N2]) Returns the substring of the expression V beginning from position N1 with the length of N2.
Если параметр N2 не указан или равен -1, то вернется подстрока от позиции N1 до конца строки.
Если параметр N2 равен 0, то вернется пустая строка.
S=trim(V[,N]) Удаляет все пробельные символы (пробелы, табуляции, переводы строк и возвраты каретки) из строки V снаружи (N=0 или не указан), слева (N=1) или справа (N=2).
S=lcase(S) Transforms the string S to lower-case.
S=ucase(S) Transforms the string S to upper-case .
S=date(format) Returns the current date/time according to the format format (See the $Date for the format description).
This function is similar to $Date macro-command but can also be used in expressions. The format argument is mandatory.
S=xlat(S) Returns the transliterated string.
This function is similar to $XLat macro command but can be used in expressions. Argument S is mandatory.
Файловые функции
Function Description
S=fsplit(path,N) Splits the path path into the components and returns theirs combination depending on the flag combination N:
ValueDescription
0x00000001Current drive in "C:" representation.
For network shares - "\\server\share"
0x00000002Rooted path in "\Program Files\Far\" representation
0x00000004Name
0x00000008Extension in ".EXT" representation or empty string, if there's no extension.
N=fexist(S) Checks if the file or folder S exists and returns 1 if true or 0 otherwise.
Usage of the '*' and '?' mask symbols is allowed in the S argument. In that case the function checks only the first occurrence of the file or folder.
This function does not work with the panels.
N=fattr(S) Returns the file system attributes of the file or folder S
AttributeDescription
0x00000001FILE_ATTRIBUTE_READONLY. The file or folder is read-only. Applications can read the file but cannot write to it or delete it. In the case of a folder, applications cannot delete it.
0x00000002FILE_ATTRIBUTE_HIDDEN. The file or folder is hidden. It is not included in an ordinary directory listing.
0x00000004FILE_ATTRIBUTE_SYSTEM. The file or folder is part of the operating system or is used exclusively by the operating system.
0x00000010FILE_ATTRIBUTE_DIRECTORY. This is a folder.
0x00000020FILE_ATTRIBUTE_ARCHIVE. The file or folder is an archive file. Applications use this attribute to mark files for backup or removal.
0x00000080FILE_ATTRIBUTE_NORMAL. The file or folder has no other attributes set. This attribute is valid only if used alone.
0x00000100FILE_ATTRIBUTE_TEMPORARY. The file is being used for temporary storage. File systems avoid writing data back to mass storage if sufficient cache memory is available, because often the application deletes the temporary file shortly after the handle is closed. In that case, the system can entirely avoid writing the data. Otherwise, the data will be written after the handle is closed.
0x00000200FILE_ATTRIBUTE_SPARSE_FILE. The file is a sparse file.
0x00000400FILE_ATTRIBUTE_REPARSE_POINT. The file or folder has an associated reparse point.
0x00000800FILE_ATTRIBUTE_COMPRESSED. The file or folder is compressed. For a file, this means that all of the data in the file is compressed. For a folder, this means that compression is the default for newly created files and subdirectories.
0x00001000FILE_ATTRIBUTE_OFFLINE. The data of the file is not immediately available. This attribute indicates that the file data has been physically moved to offline storage. This attribute is used by Remote Storage, the hierarchical storage management software. Applications should not arbitrarily change this attribute.
0x00002000FILE_ATTRIBUTE_NOT_CONTENT_INDEXED. The file or directory is not be indexed by the content indexing service.
0x00004000FILE_ATTRIBUTE_ENCRYPTED. The file or folder is encrypted. For a file, this means that all data in the file is encrypted. For a folder, this means that encryption is the default for newly created files and subdirectories.
0x00010000FILE_ATTRIBUTE_VIRTUAL. A file is a virtual file.
if file system object does not exist this function returns -1.
Usage of the '*' and '?' mask symbols is allowed in the S argument. In that case the function checks only the first occurrence of the file or folder.
This function does not work with the panels.
Панель
Function Description
N=panel.fexist(panelType,S) Checks if the file or folder S exists in the active (panelType=0) or the passive (panelType=1) panel (returns 1 if true or 0 otherwise).
Usage of the '*' and '?' mask symbols is allowed in the S argument. In that case the function checks only the first occurrence of the file or folder.
This function works only with the panels.
N=panel.fattr(panelType,S) Returns the file system attributes of the file or folder S from the active (panelType=0) or the passive (panelType=1) panel.
AttributeDescription
0x00000001FILE_ATTRIBUTE_READONLY. The file or folder is read-only. Applications can read the file but cannot write to it or delete it. In the case of a folder, applications cannot delete it.
0x00000002FILE_ATTRIBUTE_HIDDEN. The file or folder is hidden. It is not included in an ordinary directory listing.
0x00000004FILE_ATTRIBUTE_SYSTEM. The file or folder is part of the operating system or is used exclusively by the operating system.
0x00000010FILE_ATTRIBUTE_DIRECTORY. This is a folder.
0x00000020FILE_ATTRIBUTE_ARCHIVE. The file or folder is an archive file. Applications use this attribute to mark files for backup or removal.
0x00000080FILE_ATTRIBUTE_NORMAL. The file or folder has no other attributes set. This attribute is valid only if used alone.
0x00000100FILE_ATTRIBUTE_TEMPORARY. The file is being used for temporary storage. File systems avoid writing data back to mass storage if sufficient cache memory is available, because often the application deletes the temporary file shortly after the handle is closed. In that case, the system can entirely avoid writing the data. Otherwise, the data will be written after the handle is closed.
0x00000200FILE_ATTRIBUTE_SPARSE_FILE. The file is a sparse file.
0x00000400FILE_ATTRIBUTE_REPARSE_POINT. The file or folder has an associated reparse point.
0x00000800FILE_ATTRIBUTE_COMPRESSED. The file or folder is compressed. For a file, this means that all of the data in the file is compressed. For a folder, this means that compression is the default for newly created files and subdirectories.
0x00001000FILE_ATTRIBUTE_OFFLINE. The data of the file is not immediately available. This attribute indicates that the file data has been physically moved to offline storage. This attribute is used by Remote Storage, the hierarchical storage management software. Applications should not arbitrarily change this attribute.
0x00002000FILE_ATTRIBUTE_NOT_CONTENT_INDEXED. The file or directory is not be indexed by the content indexing service.
0x00004000FILE_ATTRIBUTE_ENCRYPTED. The file or folder is encrypted. For a file, this means that all data in the file is encrypted. For a folder, this means that encryption is the default for newly created files and subdirectories.
0x00010000FILE_ATTRIBUTE_VIRTUAL. A file is a virtual file.
if file system object does not exist this function returns -1.
Usage of the '*' and '?' mask symbols is allowed in the S argument. In that case the function checks only the first occurrence of the file or folder.
This function works only with the panels.
V=panelitem(panelType,itemIndex,propIndex) Queries the information for the panel element itemIndex from the active (panelType=0) or passive (panelType=1) panel. propIndex can be one of the following values:
ValueTypeDescription
0StringFile or folder name
1StringFile or folder short name
2NumberFile attributes
3StringCreation date/time
4StringLast access date/time
5StringLast modification date/time
6NumberSize
7NumberPacked size
8Number"Is selected?"
9NumberNumber of the hardlinks
10NumberSortGroup
11StringDiz-text
12StringOwner
13NumberCRC32
14NumberPosition of the element while reading from the file system
Date/time is returned in the DD.MM.YYYY HH:MM:SS format. The values order and the delimiters are determined according to the regional settings. To receive information on the current file (under cursor) itemIndex should be set to 0.
N=panel.setpos(panelType,fileName) Positions the cursor on the element with name fileName on the active (panelType=0) or passive (panelType=1) panel.
Returns the position of the element or 0 if there is no such element.
For example, the following macro creates a directory named after the current date in YYYYMMDD format or positions the cursor on this directory if it already exists.
%dt=date("%Y%m0%d");
$If (fexist(%dt))
  panel.SetPos(0,%dt)
$Else
  F7 $Text %dt Enter
$End
N=panel.setpath(panelType,pathName[,fileName]) На активной (panelType=0) или пассивной (panelType=1) панели выставляет каталог pathName и позиционирует курсор на элемент с именем fileName (если указан параметр fileName).
Возвращает 1 в случае успешной установки каталога и 0, если каталог не существует.
Например, на активной панели выставить каталог "C:\WINDOWS", на пассивной - "C:\Program Files", активную панель сделать слева и установить курсор на каталог "FAR":
$if(APanel.Left) CtrlU $End
panel.SetPath(1,"C:\\WINDOWS")
panel.SetPath(0,"C:\\Program Files","FAR")
N=panel.setposidx(panelType,indexItem) Positions the cursor on the element with index indexItem on the active (panelType=0) or the passive (panelType=1) panel.
Returns element position or 0 if such element does not exist.
Управляющие функции
Function Description
V=iif(Cond,True,False) Conditional function. If condition Cond is true then True-expression is returned, False-expression otherwise.
Среда исполнения
Function Description
V=akey(N) Returns the name or code of the key combination that was used to call this macro. N = 0 - key code is returned, N = 1 - key name is returned.
See example in the full description $AKey
S=env(V) Returns the value of an environment variable V, for instance:
$if (Env("FARLANG") == "English") ...do something... $end
B=msave(S) Stores the value of a global variable with the name S to the Vars area. Returns 0 in case of failure.
Example:
%%GlobalVars="Foo Bar"; %a=msave("%%GlobalVars");
V=clip(Cmd[,S]) Allows to perform miscellaneous manipulations on the Clipboard in accordance with the Cmd command:
CmdDescription
0Returns data from the Clipboard; the S parameter is ignored; in case of error returns 0
1Put the string S to the Clipboard; in case of error returns 0
2Add the string S to the Clipboard; in case of error returns 0
3Copy the Windows Clipboard to the internal clipboard buffer; the S parameter is ignored; in case of error returns 0
4Copy the internal clipboard buffer to the Windows Clipboard; the S parameter is ignored; in case of error returns 0
For example, put to the Clipboard a list of selected files in the CSV format (name and size):
Clip(1,"Name;Size\r\n")
Home
$While(!APanel.Eof)
  $If(!APanel.Folder && PanelItem(0,0,8))
     Clip(2,PanelItem(0,0,0)+";"+PanelItem(0,0,6)+"\r\n")
  $End
  Down
$End
See $IClip, IClip.
V=flock(Nkey,NState) Позволяет переключить состояние Lock-клавиш (NumLock, CapsLock и ScrollLock).
Клавиша Nkey:
NkeyDescription
0NumLock
1CapsLock
2ScrollLock
Состояние NState:
NStateDescription
-1получить состояние клавиши
0погасить индикатор
1включить индикатор
2переключить индикатор в противоположное состояние
В Windows 95/98/Me функция может изменять только состояние клавиш CapsLock и ScrollLock. Для линейки NT (NT/2000/XP/...) этого ограничения нет.
Функция капризная (возможно зависание компьютера), поэтому пользоваться ей надо осторожно. Например, макрос, повешенный на CtrlCapsLock (переключение между окнами) должен иметь некую обвязку:
CtrlShiftTab
%a=flock(1,-1)&1;
$while((flock(1,-1)&1)==%a)
  sleep(50)
  flock(1,2)
$end
N=sleep(N) Pause macro execution for N milliseconds. Negative sleep time is considered and error and the function returns 0.
S=waitkey([N]) Awaits any key and returns its name. If the timeout N (in milliseconds) was reached, an empty string is returned. Если параметр N не указан или равен 0, то функция будет бесконечно ждать нажатия клавиши.
N=eval(S) "Play" the macro-sequence S. If S contains syntax errors, the sequence will not be played.
FAR compiles the sequence S. If there were no errors then the state of the current macro is saved and the sequence S is executed. When S finishes the interrupted macro continues.

The function returns 0 when S is successfully compiled.

Local variables are common for both the current macro and the macro executed by eval.

For example, we want by pressing F10 to open an Explorer window with the current folder on the active panel, command line contents should be saved.
We set 2 string variables, in the Vars area, containing a macro-sequence for saving and restoring the command line:

%%CmdSave=$If (!CmdLine.Empty) %Flg_Cmd=1;
          %CmdCurPos=CmdLine.ItemCount-CmdLine.CurPos+1;
          %CmdVal=CmdLine.Value; Esc $End

%%CmdRestore=$If (%Flg_Cmd==1) $Text %CmdVal
          %Flg_Cmd=0; %Num=%CmdCurPos;
          $While (%Num!=0) %Num=%Num-1; CtrlS $End $End
then we set the following macro to F10:
$If (APanel.Visible && (!APanel.Plugin || (!APanel.Bof &&(APanel.OPIFlags & 0x20))))
  Eval(%%CmdSave)
  $If (APanel.Current == "..")
    .
    ShiftEnter
  $Else
    "%SystemRoot%\\explorer.exe /select,"
    $If (Apanel.LFN)
      CtrlN
    $End
    CtrlEnter
    $If (!Apanel.LFN)
      CtrlN
    $End
    Enter
  $End
  Eval(%%CmdRestore)
$End
Взаимодействие с пользователем
Function Description
N=msgbox([Title[,Text[,Flags]]]) Shows up the message box with the Text and the Title. Lines in the Text argument should be delimited by '\n'.
Flags can be a combination of the following values:
FlagsDescription
0x00000001Use the 'Warning' color scheme (usually white text on red background).
0x00000008Show the message lower by two lines.
0x00000010Use the left alignment for the message strings (align to center of not specified).
0x00010000Show the <Ok> button.
0x00020000Show the <Ok> and <Cancel> buttons.
0x00030000Show the <Abort>, <Retry> and <Ignore> buttons.
0x00040000Show the <Yes> and <No> buttons.
0x00050000Show the <Yes>, <No> and <Cancel> buttons.
0x00060000Show the <Retry> and <Cancel> buttons.
If the Flags argument is 0 (or omitted) then standard message box is displayed with the <Ok> button.
The return value is the number of the button the user selected (1 for the first, 2 for the second, etc.), if user canceled the message the result will be 0.
S=prompt("Title"[,"Prompt"[,flags[, "Src"[, "History"]]]]) Функция позволяет ввести одну строку текста.
Параметры: Title - заголовок диалога, Prompt - приглашения для ввода, Src - начальное значение строки ввода, History - имя истории ввода
Flags может быть набором следующих значений (аналогичным константам FIB_*):
FlagDescription
0x00000001даже если строка ввода пуста функция вернет значение пустое значение.
0x00000002используется для ввода пароля - вводимый текст на экране отрисовывается символами '*'.
0x00000004после успешного ввода, в результирующем значении S идентификаторы переменных окружения заменяются на их значения, например, если пользователь ввел '%TEMP%', то DestText будет содержать 'C:\TEMP'.
0x00000008не использовать предыдущее значение из истории, оставить строку ввода пустой; актуален, если указан непустой параметр History.
0x00000010показать разделительную линию и кнопки [Ok] и [Cancel]. Диалог увеличится на 2 строки.
0x00000020не показывать в приглашении ввода амперсанд, использовать его для определения горячей клавиши.
Функция возвращает строку - введенное пользователем значение.
Например, запросить пароль и вывести его
%s=prompt("Password","Input password:",0x02); $Text %s
Элементы управления
Function Description
N=checkhotkey(S) Returns 1 if there is a hot key S in a menu and the current 'object' is a menu, otherwise returns 0.

For example there's a hotkey '7' assigned to 'S&R' plugin in the plugins menu (F11). The following macro command sequence for the internal file editor should call 'S&R' plugin if there is a hot key assigned and the standard search dialog if not:

F11 $if (checkhotkey("7")) 7 1 $else Esc AltF7 $end
S=gethotkey(N) Returns the hotkey S for item N, if the item has a hotkey and the current "object" is a menu. Otherwise 0 is returned.
N - item position beginning with 1 (0 - current item).
N=Menu.Select(S[,N]) В меню позиционирует курсор на первый пункт, содержащий подстроку S. Поиск подстроки ведется в зависимости от указанного режима N:
ModeDescription
0полное совпадение
1совпадение с началом строки
2совпадение с концом строки
3присутствие подстроки S в пункте меню
Поиск регистронезависим. Если такого пункта нет, то ничего не делает.
Возвращает: 0=ошибка при позиционировании (нет пункта или пункт задисаблен), иначе - позицию пункта меню.
F11 $if(Menu.Select("Advanced compare",0) > 0) Enter $end
Если параметр N не указан, подразумевается полное совпадение.
V=Dlg.GetValue(ID,Type) Get misc. values of the current dialog.
ID - dialog element number (elements are numbered starting with 1; 0 - is the dialog windows itself).
Type - type of the value to get, depending on the type of the element. For the dialog windows itself (ID=0) the following values are allowed:
TypeVar typeDescription
0NumberNumber of elements in the dialog
2NumberX1
3NumberY1
4NumberX2
5NumberY2
6NumberID of the current element that has the keyboard focus
For dialog elements the following values are allowed:
TypeVar typeElementDescription
0NumberCheckBoxState of the checkbox
0NumberRadioButtonsState of the radio button
0StringListBoxValue of the current list item
0StringComboBoxValue of the current list item
0StringOtherTextual value (the FarDialogItem.Data field)
1NumberAllElement type
2NumberAllX1 relative to the dialog window
3NumberAllY1 relative to the dialog window
4NumberAllX2 relative to the dialog window
5NumberAllY2 relative to the dialog window
6NumberAlldoes the element has focus?
7NumberCheckBoxState of the checkbox
7NumberRadioButtonsState of the radio button
7StringListBoxCurrent position in the list (first list item = 1)
7StringComboBoxCurrent position in the list (first list item = 1)
7NumberOther0
8NumberAllElement flags
9NumberAllA flag that specifies that the given dialog element is the "default element".
10StringOtherTextual value (the FarDialogItem.Data field)
Returns -1 if ID is bigger than the number of elements in the dialog or the value of Type is not supported.
V=Editor.Set(Idx,Var) Change settings of the current editor instance.
IndexVar TypeDescription
0NumberTab size
1NumberExpand tabs
2NumberPersistent blocks
3NumberDel removes blocks
4NumberAutoindent
5NumberAutodetect character table
6NumberCreate new files in WIN encoding
7NumberCursor beyond end of line
8NumberBackSpace behaviour (TechInfo #13)
9NumberRepresentation of the character under cursor in the status line (TechInfo #32)
10NumberSave file position
11NumberSave bookmarks
12StringWord delimiters (TechInfo #1)
13NumberEditorF7Rules (TechInfo #18)
14NumberAllowEmptySpaceAfterEof (TechInfo #67)
The value of Var can be -1, in this case the function will not change any settings and will return the current state of the option.
Returns the previous value of the option or -1 if wrong arguments are given.
For example, a macro that moves the selected block one line down:
$IClip CtrlX %a=Editor.Set(2,1); Down CtrlV %a=Editor.Set(2,%a);
Работа с закладками
Функция Описание
N=BM.Add() Добавить текущие параметры закладки и обрезать хвост
N=BM.Clear() Очистить все закладки
N=BM.Del([Idx]) Удалить закладку с указанным индексом Idx (нумерация начинается с 1). Если параметр Idx не указан или равен 0 - удаляется текущая закладка.
N=BM.Get(Idx,M) Получить параметры закладки с индексом Idx (нумерация начинается с 1), Idx=0 - текущая закладка.
Параметр M может быть одним из следующих:
ТипОписание
0координаты строки (начиная с 1)
1координаты колонки (начиная с 1)
2позиция, соответствующая первому видимому символу текста на экране слева
3номер строки, соответствующей первой видимой строке текста на экране
N=BM.Next() Перейти на следующую закладку
N=BM.Prev() Перейти на предыдущую закладку
N=BM.Stat([M]) Получить информацию о закладках.
Параметр M может быть одним из следующих:
ТипОписание
0текущее количество закладок
Пример работы с закладками:

  

Notes

  1. Функции работы с закладками BM.XXX() доступны только в редакторе.
  2. Function arguments given in square brackets may be omitted. See default values in function description.
  3. It is impossible to use macro-language elements while recording a macro in a usual way. Macro-language elements can be added to the sequence only by editing the registry manually or by using special applications or FAR plugins.