|
Home | Switchboard | Unix Administration | Red Hat | TCP/IP Networks | Neoliberalism | Toxic Managers |
(slightly skeptical) Educational society promoting "Back to basics" movement against IT overcomplexity and bastardization of classic Unix |
|
One of most powerful options of Far Manager are Macros. There are two styles of Macro
There are multiple ways to record keyboard macros. One universal method are Programmable Keyboards. But built-in macro generators can also have built-in macrolanguage included (FAR does have such a macrolanguage) which provide much more powerful and flexible capabilities as they can access and change additional variables (internal variables). Which make built-in vastly more powerful. But basic functionality without macrolanguage is very similar.
|
FAR built-in macro recorder can be used both in panels and in built-in viewer and editor.
There are two startup key that affect behavior of FAR macros
Macros also can be written in LUA. See Lua in Far
Keyboard macros can be recorded using Ctrl-. key combination. The first key of it activates the recording and second press stops the recording and activated macro name assignment dialog.
Keyboard macro commands are recorded sequences of key presses that can be used to perform repetitive task by pressing a single hotkey. They can be viewed and edited using special plug-in that is included the standard distribution.
Each macro command has the following parameters:
Macro commands may contain OS commands that will be entered in command like and executed, allowing to create more complex constructions. They also can execute entries in user menu.
Macro commands can be used for a variety of purposes including but not limited to:
Tab c d Space ! : ; Space c d Space ! BackSlash Enter Enter Tab
Actually due a bug in FAR this does not work: FAR does not recognize !: and !\ macrovariables (parameterless macros to be exact) in command line although it should. But you can bypass this bug by creating a user menu entry
cd !#!: cd !#!\and assign it, say, character "=". Then the required macro that invokes user menu command take the following form:
Tab F2 = Tab
$Year . $Day . $Month . t x twill generate a string "2012.11.14.txt" if it was executed on November 14, 2012. See TechInfo#22 for details. Here is one such macro from FAR examples (in internal form):
<macro
area="Shell"
key="CtrlShiftF7"
flags="DisableOutput|NoPluginPanels"
description="Creation of a folder with the name equal to the current date">
<text>
%folder=date("%d.%m0.%Y");
$If (!panel.fexist(0,%folder))
F7
CtrlY
$Text %folder
Enter
$End
</text>
</macro>
The main usage of macro commands in FAR is assignment of hotkeys for calling external plugins and for overloading FAR actions.
Attention: The area of execution, to which the macro command will belong, is determined by the location in which the recording of the macro command has been started.
Currently those are 14 independent areas within which hotkeys need to be unique, but outside of which can be reused:
It is impossible to assign a macro command to an already used hotkey. When such an attempt is made, a warning message will appear telling that the macro command that is assigned to this hotkey will be deleted.
This way you can have identical hotkeys for different macro commands only in different areas of execution. Acceptable macro hotkeys hotkeys for a macro command can be:
It is impossible to enter some key combinations (in particular Enter, Esc, F1, Ctrl-F5, MsWheelUp and MsWheelDown with Ctrl, Shift, Alt) in the hotkey assignment dialog because of their special meanings. To assign a macro command to such key or key combination, select it from the dropdown list.
To record a macro command:
As the recording begins the symbol '\4FR\-' will appear at the upper left corner of the
screen.
Attention: after deleting a macro command, the key combination (hotkey) that was used for its execution will begin to function as it was meant to, originally. That is if that key combination was somehow processed by FAR or some plugin then after deleting the macro command the key combination would be processed by them as in the past.
The following execution conditions can be applied for the active and passive panels:
Plugin panel
[x] - execute only if the current panel is a plugin panel
[ ] - execute only if the current panel is a file panel
[?] - ignore the panel typeExecute for folders
[x] - execute only if a folder is under the panel cursor
[ ] - execute only if a file is under the panel cursor
[?] - execute for both folders and filesSelection exists
[x] - execute only if there are marked files/directories on the panel
[ ] - execute only if there are no marked files/directories on the panel
[?] - ignore the file selection state
Other execution conditions:
Empty command line
[x] - execute only if the command line is empty
[ ] - execute only if the command line is not empty
[?] - ignore the command line stateSelection block present
[x] - execute only if there is a selection block present
in the editor, viewer, command line or dialog input line
[ ] - execute only if there is no selection present
[?] - ignore selection state
Along with plug-ins anther powerful feature that distinguishes FAR from competition is built-in macro language It has some primitive control structures and allows to mix constructs of macrolanguage with sequences of keystrokes recorded, making macros (along with plugins) a more flexible and powerful facility. In addition of you can edit macros only via special tools/plugins.
It is very useful for automating repetitive FTP sessions when you either push to FTP server or retrieve from it set of predefined files.
The main problem with FAR macrolanguage is that it is very badly documented. Hopefully soon an old macrolanguage will be replaced by LUA which has plenty of high quality documentation (in version 3.0 LUA was integrated in FAR)
Very fragmentary description of the current macro language can be found in the accompanying documentation to the particular version of FAR. In is mostly in Russian but Google Translate is your friend ;-).
I still see not examples of this new feature.
Looks like in all three versions 1.7, 2.0 and 3.0 primitive "vendorscript was used. Several of the available commands are listed below. Please note that all language constructs start with the capital letter and are prefixed with $ sign.
Local variable name begins with a '%' character, followed by the letters of the alphabet, numbers and '_'.The scope of a local variable - current macro sequence.$AKey Call key macro.
$Break out of the current cycle.
$Continue Go to the next iteration of the loop.
$Exit Terminates the macro sequence.
$If (Expr) TruePart [$Else FalsePart] $End Allows the use of macros in the process of branching macro sequence.
$Rep (Expr) Sequence $End Allows the use of macros in a cyclical process - "Run Expr time sequence Sequence".
$SelWord Select the word under the cursor.
$Text "string" is intended to insert arbitrary text.
$While (Expr) Sequence $End Allows the use of macros in a cyclical process - "As long as the condition is true Expr perform a sequence Sequence".
$XLat Calls the transliteration.
Global variable name begins with two
characters '%%', followed by the letters of the alphabet, numbers, and the character '_'. The
scope of a global variable - current session FAR.
Variable names are case insensitive: %myStr and %MYstr is the same variable.
Assigning a value to a variable must end with the ';'
Variables can be of three types
Global variables can be stored in a special area of Vars. From this area reads FAR global variables at the start. Database representation: the global variables are stored in the table variables. Each variable has a name, value and type. Value in the database is always stored as text. The type field specifies the type of content in the field of value:
Conversion from floating-point to a string is in the format "KeyMacros / CONVFMT". By default, format "%.6g" is used.
Here is an example of use real constant PI and constant FIB_PASSWORD (0x00000002) for function prompt().
<constants> <constant name="FIB_PASSWORD", value="0x00000002", type="integer"/> <constant name="PI" value="3.14159265358979323846" type="real"/> </constants> <keymacros> <macro area="Editor" key="CtrlP" flags="DisableOutput"> %s=prompt("Password","Input password:",FIB_PASSWORD); $Text %s </macro> </keymacros>
Here are a couple of examples of macros copied from the documentation:
<macro
area="Disks"
key="Tab"
flags="DisableOutput"
description="Переход в меню выбора дисков на противоположной панели включение видимости панели в которой будет происходить смена диска, если её не было"><text>
Esc
$If (!PPanel.Visible)
$If (APanel.Left)
CtrlF2
$Else
CtrlF1
$End
$End
Tab F9 Enter End Enter
</text></macro>
<macro
area="Editor"
key="RAlt"
flags="DisableOutput"
description="выделить/(снять выделение) слово(а) под курсором"><text>
RCtrl9 CtrlRight CtrlLeft
$If (!Selected)
CtrlShiftRight
$Else
CtrlU
$End
Ctrl9
</text></macro>
<macro
area="Shell"
key="CtrlShiftF7"
flags="DisableOutput|NoPluginPanels"
description="создание папки с именем = текущей дате"><text>
%folder=date("%d.%m0.%Y");
$If (!panel.fexist(0,%folder))
F7
CtrlY
$Text %folder
Enter
$End
</text></macro>
<!--
искать тот же файл на другой панели что и на активной
F5 ShiftEnter CtrlIns - применено чтобы получить имя файла вне зависимости
пусто/непусто в cmdline и сколько выделено на панели файлов
-->
<macro
area="Shell"
key="CtrlAltLeft"
flags="DisableOutput"
description="искать тот же файл на другой панели что и на активной"><text>
<![CDATA[
clip(5)
$If (((Bof && APanel.Root) || !Bof) && PPanel.Visible)
$If (fexist(PPanel.Path+@"\\"+APanel.Current) == 1)
F5 ShiftEnter
CtrlIns Esc Tab Home
Alt< ShiftIns Esc
$End
$End
]]></text></macro>
<macro
area="Shell"
key="CtrlAltRight"
flags="DisableOutput"
description="искать тот же файл на другой панели что и на активной"><text>
<![CDATA[
clip(5)
$If (((Bof && APanel.Root) || !Bof) && PPanel.Visible)
$If (fexist(PPanel.Path+@"\\"+APanel.Current) == 1)
F5 ShiftEnter CtrlIns
Esc Tab Home Alt<
ShiftIns Esc
$End
$End
]]></text></macro>
<macro
area="Shell"
key="CtrlDown"
flags="DisableOutput"
description="Выделение следующих нижних 30 файлов"><text>
$If (!Eof)
$Rep (30)
$If (Eof)
Ins
$Exit
$Else
Ins
$End
$End
$End
</text></macro>
<macro
area="Shell"
key="CtrlUp"
flags="DisableOutput"
description="Выделение следующих верхних 30 файлов"><text>
<text>
Up
$If (Bof)
$If (!APanel.Root)
Down
$End
$Exit
$Else
Down
$End
$If (Eof)
Ins
$Else
Ins Up
$End
$Rep (29)
Up
Ins
Up
$If (Bof)
$If (!APanel.Root)
Down
$End
$Exit
$End
$End
Up
</text></macro>
<macro
area="Dialog"
key="AltP"
flags="DisableOutput"
description="сграбить весь экран в текстовый файл far-screen.out работает в области Dialog"><text>
<![CDATA[
clip(5) AltIns CtrlHome ShiftEnd ShiftPgDn Enter Esc
$If (!Shell) Esc $End
$If (Shell && !APanel.Plugin) ShiftF4 CtrlY
print("far-screen.out") Enter ShiftIns Enter Enter F2 Esc $End
]]></text></macro>
<!--
удаление файла/папки по клавише Del
если стояли на элементе .. то пытаемся удалить вышестоящую папку
если не в конце ком строки то удаляем символы в ней
-->
<macro
area="Shell"
key="Del"
flags="DisableOutput"
description="удаление файла/папки по клавише Del"><text>
<![CDATA[
$If (!CmdLine.Eof) Del $Exit $Else
$If ((APanel.Bof && !APanel.Selected) &&
(!APanel.Root || APanel.Plugin)) CtrlPgUp $End F8 $End
]]></text></macro>
<!--
перед вызовом быстрого просмотра сделать пассивную панель
максимально большего размера.
для обратной операции восстановить панели.
-->
<macro
area="Shell"
key="CtrlQ"
flags="DisableOutput"
description=""><text>
<![CDATA[
Tab $If (QView) Tab Ctrl2 Tab CtrlClear $Else Tab Ctrl6 Tab
$If (APanel.Left) $Rep (APanel.width) CtrlRight $End $Else
$Rep (APanel.width) CtrlLeft $End $End $End Tab CtrlQ
]]></text></macro>
<constants>
<constant name="FSPLIT_EXT" type="qword"><text>8</text></constant>
<constant name="FSPLIT_NAME" type="qword"><text>4</text></constant>
<constant name="ACTIVEPANEL" type="qword"><text>0</text></constant>
<constant name="PANELITEM_SELECTED" type="qword"><text>8</text></constant>
</constants>
<keymacros>
<!--
При непустой командной строке макрос не вызывается чтобы можно пользоваться первоначальной
функцией сочетания CtrlShiftIns - Поместить помеченные имена в Буфер Обмена
-->
<macro
area="Shell"
key="CtrlShiftIns"
flags="DisableOutput|EmptyCommandLine"
description="Пометить вместе с htm-файлом и парную ему папку"><text>
<![CDATA[
%Current=APanel.Current;
%Ext=substr(%Current,len(%Current)-6);
$If (%Ext=="_files")
%Name=substr(%Current,0,len(%Current)-6);
$Else
%Ext=fsplit(%Current,FSPLIT_EXT);
%Name=fsplit(%Current,FSPLIT_NAME);
$End
$if (%Ext==".htm" || %Ext==".html")
panel.setpos(ACTIVEPANEL,%Name+".files")
panel.setpos(ACTIVEPANEL,%Name+"_files")
$end
$if (%Ext==".files" || %Ext=="_files")
panel.setpos(ACTIVEPANEL,%Name+".htm")
panel.setpos(ACTIVEPANEL,%Name+".html")
$End
$if (APanel.Current!=%Current)
$If(!panel.item(ACTIVEPANEL,0,PANELITEM_SELECTED)) Ins $End
panel.setpos(ACTIVEPANEL,%Current)
$If(!panel.item(ACTIVEPANEL,0,PANELITEM_SELECTED)) Ins $End
$End
mmode(1,2)
]]></text></macro>
</keymacros>
If ScrollLock is on force Left/Right to do horizontal scrolling
[HKEY_CURRENT_USER\Software\far2\KeyMacros\Editor\Right]
"Sequence"="$if(flock(2,-1) == 1) editor.pos(1,5,editor.pos(0,5)+1); $else Right $end"
"DisableOutput"=dword:00000001
[HKEY_CURRENT_USER\Software\far2\KeyMacros\Editor\Left]
"Sequence"="$if(flock(2,-1) == 1) editor.pos(1,5,editor.pos(0,5)-1); $else Left $end"
"DisableOutput"=dword:00000001
In the Vars we define two string variables which save and restore the contents of 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
After that we need to assign a macro to key 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
|
Switchboard | ||||
Latest | |||||
Past week | |||||
Past month |
Post by Acerbic " Tue 23 Apr, 2013 22:53
hotkeys / remapping key bindings.
This is the simplest. You want one custom key (or combination with Ctrl, Shift, Alt modifiers) do what another key (combination) already does. It is one for one replacement.2. Your typical macro. Press one key to emulate a sequence of many keys.
Its not much different from just a hot key. You press a key - it is treated as if you pressed some fixed predefined string of keys.3. Script.
Now this is interesting. Script involves logic and decision making, not just some fixed reaction. A script has means to analyze current situation and affect Far Manager in non-trivial ways. Requires programming skills to create, but luckily the are many scripts already written and you may find one just fitting your needs.4. Plugin.
Well, this is a moot point. With the course Far development is following now the gap between a complex script and a full fledged plugin is closing rapidly. As of right now, a script has most of functional capabilities a plugin has, it has access to both macro API and plugin API, in the latest builds a macro script can be started by an event, not just by a key pressed and so forth...History and identification of obsolete.
FAR Manager has traveled a long way from its early versions and so did its macro capabilities. In Far1 and Far2 the configuration was stored in Windows registry, including macros. In Far3 configuration was moved to SQLite database files located in user's profile folder. But later it was decided that it would be better to allow users simpler access to macros and they were moved from a database to individual files (still inside user's profile folder). Also, parallel to moving macro definitions to external files, the macro language was changed to LUA.In addition to that, there is a very popular plugin called "MacroLib". It provides extended macro features on top of built-in system. It used to overlay old macro language, but then switched to LUA as well. It always stored macros in external files.
So, what to look out for to spot outdated manuals / macro recipes?
1) *.reg files. Partial and full configurations were distributed as reg import files in times of Far1 and Far2. That included macros. No *.reg files are used by Far3 plugins or Far3 itself, but some old (ANSI) Far1 plugins can still use them. Any macros contained in them won't work in Far3.
2) *.farconfig files. Those are XML text files containing configurations for Far3. They are still used for other parts of configuration (coloring schemes and such) but not for macros anymore.
3) Old macro language. It contained keywords like "$IF" "$ELSE" - denoted by dollar sign.
4) Old MacroLib files *.fml - new MacroLib macro files use "fmlua" extension.
It is important to note that internal help in Far (called by "F1") is massively lagging behind development - hence this article.
What now?
At present, by means of storage macros fall in three groups.1) Files of the built-in macro system. *.lua
Located in %FARPROFILE%/Macros/internal and %FARPROFILE%/Macros/scripts2) MacroLib files *.fmlua.
By default are located within plugin's folder, but it can be configured to read macros from any user defined path (or several).3) Other macro processing plugins. "Lua4Editor", for example. I don't know much about these, you are on your own here, folks.
Important warning! There are plugins written in LUA. These are something different from macros. They are legit plugins with all the things a "usual" plugin has (like being listed in plugins' menu "F11"). Except they are written in LUA and distributed as source files. They should not confuse you as they lie in their folders in %FARHOME%/Plugins
Conversion.
It is best to rewrite your macros in LUA from scratch. If they are few and simple, it won't take much effort. If they are complex, conversion is likely to fail to do it automatically. But if you are still interested in doing things hard way, there are few tools to help you. They were meant as quick fixes for transition period and aren't supported anymore, probably.I. Far1, Far2 -> Far 3 2x3 perl converter
This tool is used to convert old configuration from registry to database. This includes macros.
The result will be a bunch of XML files containing far configurations and macros in the old language.II. Translation from old language to the new one is done by Macro2Lua Converter plugin. The readme is in Russian, but here is an excerpt regarding main usage via command line
>M2L: convert <input file> <output file> [<syntax>]
where <syntax> is optional input format specifier and is one of following:
xml_file, xml_macros, xml_keymacros, xml_macro, fml_file, fml_macro, chunk, expression. General file format is the part before underscore, the specific section of a file is the part after underscore. "chunk" and "expression" are some kind of raw macro pieces of texts.
The result should be a XML file (<farconfig>...</farconfig>) with macros translated to LUA inside of it or a MacroLib fmlua file if original was *.fml and corresponding syntax was specified.III. Far3 2927-3000 -> Far3 3001+
Now you need an older version of Far3 (pre3001). You import your macros to Far per usual command, then use a script provided in the following forum thread:
Macros have been moved from macros.db to filesManaging confusion.
While all macros are written in LUA, file contents are not interchangeable as of right now. It means that you can't rename X.fmlua to X.lua, move it to %FARPROFILE%/Macros/scripts and expect it to work. Likewise you can't just move files from /internal to /scripts.Luckily, with few rules I am about to explain, you won't get lost in all of the LUA files lying around.
1) Don't touch your internals!
Files in %FARPROFILE%/Macros/internal are to be manipulated (created/edited/deleted) by FAR Manager itself. And while it is possible to edit them manually, better to leave them alone. Unless you really know what are you doing. Or just feeling adventurous.2) MacroLib files are always named *.fmlua, so you can never confuse them with native script files, even if you configured the MacroLib so they are located in the same directory.
3) User-made native script files are located in %FARPROFILE%/Macros/scripts and are named *.lua. They are read at Far launch, but you can make Far to re-read the folder via command line (more on that later).
So, only (2) and (3) are in user's management and they are different in names, location and internal structure.
But there are similarities too.
1) Both MacroLib and native macros have a concept of "Area of execution" - basically, a broad condition limiting macro effect. Typical are "Editor" - when editor is open, "Shell" - when file panels are in focus, etc...2) In addition to general area, some more conditions might be specified for activation of a macro. Like passive panel being visible, command line not being empty and similar. These conditions/flags are legacy carried over from times when macro language was primitive and things like that were hard to check in script itself. Alternatives are being developed (like custom function conditionals in native scripts) but there is no sign that old flags will be abandoned yet.
3) And finally, there are two flags that control execution of the macro itself. One is to disable/enable intermediate visual output during macro execution (reduces flicker of menus and dialogs being open/closed, for example), another is to control if plugins can intercept keyboard events generated by macro. No other macro can intercept current macro while it is executing - so you don't have to worry about nasty macro interferences.
Out of the box.
In the beginning of time the macro language was ugly and everyone was sad. And few of the developers raised their voices: "Look! There in the great outside lies shiny LUA. Let us take it for ourselves, let us bind it to our manager and then we won't be suffering dollar-signed keywords no more." And so they did. And night turned day, and day turned night, and the Moon died and was born again as they tinkered and meddled and compiled and debugged. Seasons passed by, but finally, the day has come and their labor was over.
And they stood proud among men and shouted: "Behold this LuaMacro plugin! We can rework our ugly macros into LUA, we have the technology now. But wait! There's more: we can write plugins in LUA as well, if we desire so." And everyone rejoiced.
And gathered developers of Far and saw what their brethren did, and saw that it was good. So good in fact, they put the new plugin in the core package and abandoned their old ways of macros.So, native macro capabilities are provided by LuaMacro plugin, which is distributed with Far itself as part of its core package. The plugin has no configuration dialog, but has a list of commands to manipulate it:
When "load" and "unload" operations are concerned, only native macros are affected. I.e. those *.lua that are located in /internal/ and /scripts/ . MacroLib macros are not touched. List of all currently loaded native macros is available in Far built-in help "F1". That part of help is not translated to English yet, and its not very convenient in operation anyway. Check this macro out though.
- lm: unload - Far forgets all macros. They are still on disk and can be loaded back with next command.
- lm: load - makes Far discard all macros and then re-read them from directories anew.
- lm: post <sequence>|@<filename> - executes a macro code immediately. Either a "raw" piece of code typed in command line, or same raw code saved in a file. File name is prefixed with "@" symbol.
- lm: check <sequence>|@<filename> - same as above. Except the macro is not executed but checked for syntax errors.
- lm: save - saves changes made to "internal" macro files. Useful if you have "Auto save setup" option turned off.
Note. "lm:" commands are similar to ones provided by FarCommands plugin via "macro:" and "far:macro " prefixes. There was a difference in that FarCommands used "<" symbol to specify filename, but now it supports both "<" and "@" for this.
It is time now to explain why some macros are put in /internal/ and others in /scripts/. Its fairly simple - "internal" is a codename for "recorded" and all the recoded macros go there. More on recorded macros is in the "Hotkeys / Macro use case" chapter.
User-made macros are to be placed in /scripts/. Sadly, there's no comprehensible manual on how to write them. One is reduced to scavenging for bits and pieces of knowledge by perusing Far's changelog and dissecting macros written by others (SimSU macro pack for example, topic in Russian forum: http://forum.farmanager.com/viewtopic.php?f=15&t=7075). Here is a script for the Editor that pastes a macro template on "Ctrl+F11" by Shmuel: InsertMacro.lua.7zMacroLib.
This is what all the cool kids use. MacroLib is a plugin that provides somewhat extended functionality to macros. It is built on top of native macro system, so 99% of the code working for "regular" macro will work for MacroLib as well.
Project's main page: http://code.google.com/p/far-plugins/wiki/MacroLib, download page: http://code.google.com/p/far-plugins/downloads/list?q=MacroLib, documentation (Russian): http://code.google.com/p/far-plugins/wiki/FML.
MacroLib files are named *.fmlua and are located in one or several directories designated by user in configuration dialog. The dialog allows you to update macros from disk and shows you a very neat list of all macros currently loaded with ability to sort, filter, run a macro from the list.
MacroLib used to have many advantages over built-in system, but nowadays Far has caught up for the most part and is ahead in some experimental things (like events). However, there are two things *.fmlua scripts have over *.lua ones.
1) You can use modifiers to your assigned hotkeys, such as "Hold" (macro is invoked after the key was held for a certain period of time), "Double"(on double click or double key tap), "Release" (macro is called on key being released, rather than being pressed).
2) You frame your macro code in double curly brackets for extra swag {{ }}.Hotkey / Macro use case.
Can't get used to saving edited file by "F2"? Too lazy to run through menus every time you want to view your current Folder Shortcuts? Then this chapter is for YOU. This chapter covers a very simple usage of Far macros - redefining hotkeys for existing actions and creating hotkeys for actions that don't have them by default.
The easiest way to do said things is by using "Recorded Macro" feature. The Far Manager has an ability to record your actions (keyboard events) and assign them to a specific key, pressing which will replay your actions. This function is in there from Far1 and is explained in "F1" Help, but I will rehash it for you anyway.
You start recording by pressing "Ctrl+." (Control key plus dot key) or "CtrlShift+.", a little red "R" letter appears in the top-left corner and your following key presses will be recorded. You continue to use Far as usual, doing things you want to be put in the macro, or just pressing one key you want to be remapped. Then you finish recording by pressing "Ctrl+." or "CtrlShift+." again. Then you will be asked for a key to which this macro will be assigned, you can select one from a drop-down list with a mouse or just press the desired combination, then "Enter". At this moment an optional dialog might appear to configure additional parameters of you macro.
So,
1. "Ctrl+." or "CtrlShift+."
2. Do stuff on record.
3. "Ctrl+." or "CtrlShift+."
4. Select a desired key to assign to.
5. (optional) Configuration dialog.If you finish recording with "CtrlShift+." on step 3 you will be shown a dialog on step 5. Otherwise you won't be. To know more about this dialog, press "F1" while in there, its covered in the Help.
Starting the recording with "CtrlShift+." puts a "NoSendKeysToPlugins" flag on your macro, which means that during macro playback plugins won't be able to react to keyboard events generated by this macro - it forces plugins to ignore this macro in that regard.If you made a mistake in your macro during recording you may interrupt the recording by usual "Ctrl+." and then hit "Esc" when asked about desired key.
If you select a key that is already taken by a macro, you will be asked if you want to overwrite previous macro. This means you cannot have two recorded macros on the same key in the same area of execution. You can, however, have one for each area (one in Editor, one in Viewer, etc.)
If you need to delete a macro you previously recorded, you create an empty macro for the key you want to free: "Ctrl+.", "Ctrl+.", the key. Then select "yes" to confirm deletion.If you have "F9"->"Options"->"System Settings"->"Auto save setup" option turned on, then every change to your recorded macros (creation, modification, deletion) will be immediately saved to files. Otherwise you can use lm: save command to save your recorded macros or press "Shift+F9" to save full setup.
If you want to know what macros are already recorded, you can navigate to %FARPROFILE%/Macros/internal. It is possible delete macros in there, just don't forget to use lm: load command to update, or restart Far.Example: lets bind a hotkey to "File associations" menu.
0. (preparation) Make sure you are in the Shell area of Far, its where two panels with files and folders are.
1. Press "Ctrl+." and make sure the red "R" letter appeared.
2. Press "F9" to move input focus to Far's menu (usually is the top line of the window), then "c" for commands, then "a". Now, if done right the "File associations" menu is on screen.
3. Press "Ctrl+."again, a little "Define macro" box should pop up. Press "Ctrl+Shift+a" and confirm that corresponding key code appeared in the box ("CtrlShiftA").
4. Press "Enter" and enjoy a new quality of life improvement you just created for yourself. Now every time you press "Ctrl+Shift+a" combo in Far shell, the menu will instantly appear.Script use case.
"Script" is a program that runs within/by other program (as opposed to one run by CPU/OS). Scripts in Far evolved from macros to a point when macros themselves are considered primitive cases of scripting. Being programs, scripts require "Programming / Coding" skill to be created, therefore, if you intend to use Far to its fullest potential you might want to invest few skill points in it on your next level up. Alternatively, you can utilize macros written by someone else - just copy the files in appropriate folders.
As mentioned before, Far uses LUA language for scripting. From within the script you have access to
1) Far (plugin) API - functions of Far that are available to plugins.
2) Far macro API - some specific functions that were available in old language. These overlap "Plugin API" to some extend and considered legacy API. Better use "Plugin API" where possible.
3) Custom functions exported by plugins - some plugins export their functions to be called from macro. Those depend on plugin being installed and loaded, of course.
4) LUA libraries - native to LUA (see language manual) plus few libraries additionally shipped with LuaFar ("bit64", "win" - gate to Win API, Selene Unicode)
5) Far UI - you can control Far simply by issuing keyboard/mouse commands to it. Why bother finding a function that will open Editor for file under cursor when you can just send "F4" to Far?Your main source of information about Far APIs is in %FARHOME%\Encyclopedia files. Lets look at them.
Damn, its kinda depressing, ain't it? Luckily for you, I have a magical artifact that will allow you to understand Russian: abracadabra. Paste a link to Russian website or text fragment and hit "Enter".
- "FarEncyclopedia.ru.chm" - includes (1) and (2), in Russian. Macro API is outdated (pre-LUA). There's an online version too: http://api.farmanager.com/ru/
- "luafar_manual.chm" - originally a LuaFar plugin manual (writing plugins in LUA), but we can use it in scripts too. Covers (1) in LUA in English. Very spartan - most of the functions have no textual descriptions, only input parameters and result values (implies ability to read "FarEncyclopedia.ru.chm"). For the most part it is not a problem though, functions' names are self-descriptive.
- "macroapi_manual.chm" - mapping of (2) to LUA. Again, almost no descriptions.
And Acerbic saves the day once again! You are welcome.
To sum it up: you will use "luafar_manual.chm" in conjunction with translated online encyclopedia for Far plugin API reference and "macroapi_manual.chm" in conjunction with this link for Macro API reference.
I found this script very helpful: lua_explorer. It allows you to browse Lua tables/values/functions soup available to LUA script. Thread on the forum.
astral2k5 " Mon 18 Mar, 2013 14:19
Hi,
I've recently updated to FAR 3.0 and running the latest stable version.
I'm trying to add CTRL-F, F3 macros for editor and other shortcuts.
Can you please let me know how can I do this?Btw, i've downloaded the RH_Macros (http://plugring.farmanager.com/plugin.php?pid=889&l=en) files with a lot of .lua scripts, but don't know how to use them. Also in plugins menu, there is no Lua Macro listed.
Thanks!
Aidar " Tue 19 Mar, 2013 12:31
May be, this answer can help you.
by pepak " Wed 10 Aug, 2011 16:51
It's my first attempt at FAR's macro language, so please bear with me and point out any errors I made. The code is heavily based on the original Maximus5's code, except that I opted to remove dependency on menu, and use a number of keys instead:
- ALT+F1 = copy to left
- ALT+F2 = copy to right
- ALT+F3 = compare using WinMerge (or any other external utility)
- CTRL+F1 = edit left
- CTRL+F2 = edit right
The code for ALT+F3 seems especially cumbersome to me, surely there is a better way to do it?
- Code: Select all
// Far2
const DirSyncID = 0x44725363
// Far3
//const DirSyncID = "F5AE7C40-F8D0-443E-82A4-285DBFB4FF69"macro Descr="DirSync - edit left" Area="Editor" Key="CtrlF1"
{{
$if (callplugin(#%DirSyncID,1)==0) $Exit $end
$if (env("DirSyncFileInfo")=="")
MsgBox("DirSync info","Current editor is not DirSync report\nor current line is not difference info",1)
$Exit
$end$if (!fexist(env("DirSyncFileLeft")))
MsgBox("DirSync info","File on the left does not exist",1)
$Exit
$end
ShiftF4 print(env("DirSyncFileLeft")) Enter
}}macro Descr="DirSync - edit right" Area="Editor" Key="CtrlF2"
{{
$if (callplugin(#%DirSyncID,1)==0) $Exit $end
$if (env("DirSyncFileInfo")=="")
MsgBox("DirSync info","Current editor is not DirSync report\nor current line is not difference info",1)
$Exit
$end$if (!fexist(env("DirSyncFileRight")))
MsgBox("DirSync info","File on the right does not exist",1)
$Exit
$end
ShiftF4 print(env("DirSyncFileRight")) Enter
}}macro Descr="DirSync - copy to left" Area="Editor" Key="AltF1"
{{
$if (callplugin(#%DirSyncID,1)==0) $Exit $end
$if (env("DirSyncFileInfo")=="")
MsgBox("DirSync info","Current editor is not DirSync report\nor current line is not difference info",1)
$Exit
$end$if (!fexist(env("DirSyncFileRight")))
MsgBox("DirSync info","File on the right does not exist",1)
$Exit
$end
Home Del Del Del Del print("<---") Right
}}macro Descr="DirSync - copy to right" Area="Editor" Key="AltF2"
{{
$if (callplugin(#%DirSyncID,1)==0) $Exit $end
$if (env("DirSyncFileInfo")=="")
MsgBox("DirSync info","Current editor is not DirSync report\nor current line is not difference info",1)
$Exit
$end$if (!fexist(env("DirSyncFileLeft")))
MsgBox("DirSync info","File on the left does not exist",1)
$Exit
$end
Home Del Del Del Del print("--->") Right
}}macro Descr="DirSync - compare" Area="Editor" Key="AltF3"
{{
$if (callplugin(#%DirSyncID,1)==0) $Exit $end
$if (env("DirSyncFileInfo")=="")
MsgBox("DirSync info","Current editor is not DirSync report\nor current line is not difference info",1)
$Exit
$end$if (!fexist(env("DirSyncFileLeft")))
MsgBox("DirSync info","File on the left does not exist",1)
$Exit
$end
$if (!fexist(env("DirSyncFileRight")))
MsgBox("DirSync info","File on the right does not exist",1)
$Exit
$end// Switch to panels
%PanelCount=0;
$While (!Shell)
%PanelCount=%PanelCount+1;
CtrlTab
$End// Save command line
$If (!CmdLine.Empty)
%Flg_Cmd=1;
%CmdCurPos=CmdLine.ItemCount-CmdLine.CurPos+1;
%CmdVal=CmdLine.Value;
Esc
$End// Run the compare
print("winmerge \"")
print(env("DirSyncFileLeft"))
print("\" \"")
print(env("DirSyncFileRight"))
print("\"")
Enter
sleep(100)// Restore command line
$If (%Flg_Cmd==1)
$Text %CmdVal
%Flg_Cmd=0;
%Num=%CmdCurPos;
$While (%Num!=0)
%Num=%Num-1;
CtrlS
$End
$End// Return back
$While (%PanelCount > 0)
%PanelCount=%PanelCount-1;
CtrlShiftTab
$End
$Exit;}}
forum.farmanager.com
by Joco1114 " Mon 27 Jul, 2009 14:50
I would like to switch the build-in F5, F6 and F8 to Background Copy commands. (F11-b-1, 2 and 3)
The problem: I would like to use these macros only in Shell mode, not in archive mode.
Here is my solution, that isnt work!
REGEDIT4[-HKEY_CURRENT_USER\Software\Far2\KeyMacros\Shell\F5]
[HKEY_CURRENT_USER\Software\Far2\KeyMacros\Shell\F5]
"Description"="Copy with Background Copy"
"Sequence"="$If(Shell) F11 b 1 $Else F5 $End"
"DisableOutput"=dword:00000001
"EmptyCommandLine"=dword:00000001
"NotEmptyCommandLine"=dword:00000000
What I need in Sequence? Can I get syntax about it?
Joc
Top
- Joco1114
- Posts: 22
- Joined: Thu 23 Jul, 2009 13:39
- Last Visit: Sat 28 Aug, 2010 13:53
Re: Alternative F5, F6, F8
by Centaur " Mon 27 Jul, 2009 15:48
If you start macro recording with Ctrl+. and end it with Ctrl+Shift+., a macro settings dialog appears where you can specify that it should only run when neither the active nor passive panels are plugin panels.Top
Centaur- Posts: 1083
- Joined: Tue 05 Apr, 2005 20:09
- Last Visit: Fri 30 Nov, 2012 15:53
- Location: Novosibirsk, Russia
Re: Alternative F5, F6, F8
by Andrey Budko " Mon 27 Jul, 2009 15:54
Joco1114:The problem: I would like to use these macros only in Shell mode, not in archive mode.[HKEY_CURRENT_USER\Software\Far2\KeyMacros\Shell\F5]
"Sequence"="F11 b 1 F5"Background copy\Configure plugin\[x] Check destination panel type
Top
Andrey Budko- Posts: 1196
- Joined: Fri 01 Apr, 2005 14:03
- Last Visit: Fri 30 Nov, 2012 10:31
Re: Alternative F5, F6, F8
by Joco1114 " Mon 27 Jul, 2009 15:58
I cant belive, it is so easy! Thank you friends!Joc
Top
- Joco1114
- Posts: 22
- Joined: Thu 23 Jul, 2009 13:39
- Last Visit: Sat 28 Aug, 2010 13:53
Re: Alternative F5, F6, F8
by Andrey Budko " Mon 27 Jul, 2009 15:59
Joco1114:I cant belive, it is so easy! Thank you friends!
BCopy\macros\BGcopy.cmd F5
forum.farmanager.com • View topic - Left and Right keys to enter folder
by michaelang " Mon 26 Jul, 2010 06:29
I sort of like Gnome-Commander using Left or Right key to get into folders, so I set my Macros as below, hope it is useful to someone.[HKEY_CURRENT_USER\Software\Far2\KeyMacros\Shell\Left]
"Sequence"="CtrlPgUp"
"DisableOutput"=dword:00000001
"NoSendKeysToPlugins"=dword:00000001
"NoFiles"=dword:00000001[HKEY_CURRENT_USER\Software\Far2\KeyMacros\Shell\Right]
"Sequence"="CtrlPgDn"
"DisableOutput"=dword:00000001
"NoFiles"=dword:00000001
"NoSendKeysToPlugins"=dword:00000001Top
michaelang- Posts: 14
- Joined: Sat 17 Jan, 2009 08:48
- Last Visit: Thu 08 Nov, 2012 07:18
Re: Left and Right keys to enter folder
by Игорь Юдинцев " Mon 26 Jul, 2010 06:43
%FARHOME%\Addons\Macros\Lynx-mot.reg
forum.farmanager.com
by richli " Fri 12 Jun, 2009 16:08
Hello,First, Far is one of the best OFMs I've ever used. It will be the best if it uses Windows PowerShell as default shell. So far, I am happy enough that FarNet and PowerShellFar work very well for me. Thank you so much!
Attached are two Macros I put up together and found useful. AltPgUp works the same as Alt-i of MC(4.6.2). AltPgDn simulates Alt-o of MC. They are not in Addons\Macros of Far installation(2.0 build 981 x86).
Dr. Nikolai Bezroukov also mentioned the kinds of feature in the Suggestions section of his book(ch05/shtml) on OFM at softpanorama.
""""""""""
F5-F5 should synchronize active and passive panels. Alt-PgDN should open the directory under the cursor (or archive under the cursor) directory on the passive panel, Alt-PgUp should show the parent directory on the passive panel as required by OFM2004.
"""""""""Please review the appended.
thanks
zhenge
+++++++++++++++++++++
[HKEY_CURRENT_USER\Software\Far2\KeyMacros\Shell\AltPgDn]
"Description"="Use AltPgDn to open the directory under the cursor on the passive panel"
"Sequence"="Tab c d Space Ctrl; Enter Tab Down"
"DisableOutput"=dword:00000001
"NoFiles"=dword:00000001
"NoSendKeysToPlugins"=dword:00000001[HKEY_CURRENT_USER\Software\Far2\KeyMacros\Shell\AltPgUp]
"Description"="Use AltPgUp to open the parent directory on the passive panel"
"Sequence"="Tab c d Space CtrlShift] Enter Tab"
"DisableOutput"=dword:00000001
+++++++++++++++++++++++Top
- richli
- Posts: 5
- Joined: Fri 12 Jun, 2009 15:51
- Last Visit: Tue 21 Dec, 2010 16:48
Re: Macros AltPgUp and AltPgDn
by NightRoman " Fri 12 Jun, 2009 17:07
richliFor your AltPgDn I use another sequence, which uses "Same Folder" feature of the standard FAR Commands plugin (see settings):
- Code: Select all
═════════════════════════ FAR Commands ════
[x] Add "Same Folder" to the Plugins menu
The sequence:
F11 0 Tab CtrlPgDn Tab
.. where '0' is the hotkey of "Same Folder" in the Plugins menuThe advantage of my approach is that archives are treated in the same way as directories. Even more, this actually "works" for some other file types, too, it depends on CtrlPgDn action for them (see file associations).
Top
- NightRoman
- Posts: 4701
- Joined: Fri 18 Aug, 2006 13:52
- Last Visit: Sat 01 Dec, 2012 00:12
- Location: Cambridge, UK
Re: Macros AltPgUp and AltPgDn
by NightRoman " Fri 12 Jun, 2009 17:32
(offtopic )
It will be the best if it uses Windows PowerShell as default shell.At first I used to think so, too. Now I am not so sure. Actually I even have strong doubts. There will be rather long way of PowerShell adoption and this process should not be forced for many reasons. One of them is that PowerShell is still at its "beta" age, no matter how they call it: RTM, CTP, RC...
But PowerShell is still one of the best scripting tools for Windows, this is the fact, too. The way how it is integrated into Far is actually quite good, IMHO, at least for now. Still, I am always interested in fresh ideas and in reasonable criticism:
viewtopic.php?f=39&t=3885
Google matched content |
...
FAR Manager. Macros and whatnot. - forum.farmanager.com
Society
Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers : Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism : The Iron Law of Oligarchy : Libertarian Philosophy
Quotes
War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda : SE quotes : Language Design and Programming Quotes : Random IT-related quotes : Somerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose Bierce : Bernard Shaw : Mark Twain Quotes
Bulletin:
Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 : Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law
History:
Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds : Larry Wall : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOS : Programming Languages History : PL/1 : Simula 67 : C : History of GCC development : Scripting Languages : Perl history : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history
Classic books:
The Peter Principle : Parkinson Law : 1984 : The Mythical Man-Month : How to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite
Most popular humor pages:
Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor
The Last but not Least Technology is dominated by two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt. Ph.D
Copyright © 1996-2021 by Softpanorama Society. www.softpanorama.org was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) without any remuneration. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.
FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.
This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...
|
You can use PayPal to to buy a cup of coffee for authors of this site |
Disclaimer:
The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the Softpanorama society. We do not warrant the correctness of the information provided or its fitness for any purpose. The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.
Last modified: March, 12, 2019