Интуитивное использование методов монте-карло с цепями маркова

Содержание:

Редактор

F4 (в редакторе) — поиск с заменой

F6 (в редакторе) — поиск с помощью регулярного выражения

Shift-Del (в редакторе) — удалить блок (и положить его в clipboard)

Shift-Ins (в редакторе) — вставить блок из буфера (работает даже в другой консоли!!!) Можно редактировать два и более файлов на разных консолях и гонять блоки между ними.

Shift+F3 — Начать выделение блока текста. Повторное нажатие F3 закончит выделение

Shift+F5 — Вставка текста из внутреннего буфера обмена mc (прочитать внешний файл)

Meta+i — Переключение режима «Автовыравнивание возвратом каретки», удобно при вставке отформатированного текста из буфера обмена

Meta+l — Переход к строке по её номеру

Meta+q — Вставка литерала (непечатного символа).См. таблицу ниже

Meta+t — Сортировка строк выделенного текста

Meta+u — Выполнить внешнюю команду и вставить в позицию под курсором её вывод

Ctrl+f — Занести выделенный фрагмент во внутренний буфер обмена mc (записать во внешний файл)

Ctrl+k — Удалить часть строки до конца строки

Ctrl+n — Создать новый файл

Ctrl+s — Включить или выключить подсветку синтаксиса

Ctrl+t — Выбрать кодировку текста

Ctrl+u — Отменить действия

Ctrl+x — Перейти в конец следующего

Ctrl+y — Удалить строку

Ctrl+z — Перейти на начало предыдущего слова

Meta+Enter — Диалог перехода к определению функции

Meta+- — Возврат после перехода к определению функции

Meta++ — Переход вперед к определению функции

Meta+n — Включение/отключение отображения номеров строк

tab Отодвигает вправо выделенный текст, если выключена опция «Постоянные блоки»

Meta-tab Отодвигает влево выделенный текст, если выключена опция «Постоянные блоки»

Shift+Стрелки Выделение текста

Meta+Стрелки Выделение вертикального блока

Meta+Shift+- Переключение режима отображения табуляций и пробелов

Meta+Shift++ Переключение режима «Автовыравнивание возвратом каретки»

Теги: bash,linux,mc

Формат описания файла настроек внешнего вида (скин-файла)

Загрузка скин-файла

Скин-файл может задаваться следующими способами (в порядке убывания приоритета):

  • параметр командной строки -S <скин> или —skin=<скин>
  • переменная окружения MC_SKIN
  • в конфигурационном файле параметр skin в секции
  • файл ${sysconfdir}/mc/skins/default.ini (например, /etc/mc/skins/default.ini)
  • файл ${datadir}/mc/skins/default.ini (например, /usr/share/mc/skins/default.ini)

Параметры в трёх первых случаях могут содержать абсолютный путь к скин-файлу либо просто название скина (с расширением .ini либо без него). В данном случае поиск скин-файла будет происходить по следующим каталогам (до первого нахождения):

  • ~/.mc/skins/
  • /etc/mc/skins/
  • /usr/share/mc/skins/

Описание секций

содержит информацию, относящуюся к самому скин-файлу.

description

содержит описания цветовых пар для групп подсветок имен файлов. Названия параметров в секции должно совпадать с
названиями секций в файле подсветки.

содержит описание элементов, используемых повсеместно.

_default_

selected

marked

markselect

gauge

input

reverse

содержит описания элементов диалоговых окон (кроме сообщений об ошибках).

_default_

dfocus

dhotnormal

dhotfocus

содержит описания элементов диалога об ошибках.

_default_

errdhotnormal

errdhotfocus

содержит описание элементов, отображающихся в меню. Это касается как системного меню (вызываемого клавишей F9), так и пользовательских меню (F2 в панелях или F11 в редакторе).

_default_

entry

menuhot

menusel

menuhotsel

содержит описания цветов для окна отображения помощи.

_default_

helpitalic

helpbold

helplink

helpslink

содержит описания элементов редактора

_default_

editbold

editmarked

editwhitespace

linestate

содержит описания элементов редактора

viewunderline

Линии для отрисовки рамок

Линии задаются в секции в скин-файле. По умолчанию используются одинарные линии, но возможно переназначить на использование любых utf-8 символов, похожих на линии

Описание параметров секции :

lefttop

righttop

centertop

centerbottom

leftbottom

rightbottom

leftmiddle

rightmiddle

centermiddle

horiz

vert

thinhoriz

thinvert

Usage

The below section provides a short overview on usage of Midnight commander. References to and the Help function (, available in every dialog) are made in this article as .

Tip: All hints are available in .

Interface

In prominent view are two vertical panes. Either can list directory contents, show a plain text preview, file details, or a directory tree (see ). File operations are accessible through the function keys or the mouse. More options are visible in a dynamic user menu () and option menu (). Keys above ( up to ) are accessible through . Menu and dialog options have one letter highlighted — pressing this letter (or inside a text entry) directly activates the respective option.

Below, a command line is visible, connected to a subshell. This shell is generally of the same type mc was launched from, and may be switched to at will (), see . On this command line, cd is interpreted by Midnight Commander, and not passed to the shell for execution. As such, special completion (such as from Zsh) is unavailable. Files in the pane interact with the command line; for example, copies the name of a (selected) file to the command line.

Keybindings are generally similar to GNU Emacs. A more strict emacs keymap can be enabled (see ). New users may however use Lynx-like (arrow) keybindings (enabled in ) and mouse clicks for navigation.

Modules

These can be called via the mc interface (with Use internal enabled in ), or separately as symbolic links to the mc binary.

  • mcedit — Text and binary file editor, with regex replace, syntax highlighting, macros and shell piping, see
  • mcview — Text and hex viewer with goto marks and regex search
  • mcdiff — Compares and edits two files in-place ()

Per instance, multiple modules can be run concurrently () (see ). External editors may be used instead, and parameters configured accordingly.

Полезные настройки

левая\правая панель — формат списка. позволяет задать пользовательский формат вывода информации (чтобы посмотреть доступные поля нажмите

  • Конфигурация
    • детали операции/подсчитывать размер — в совокупности эти две опции дадут более информативное окно копирования файлов (а если убрать, то копирование будет работать гораздо быстрее)
    • Автоматически сохранять настройки — полезно чтобы постоянно не нажимать «сохранить настройки»
  • Внешний вид
    • строка подсказки — дасть немного больше места на экране если убрать (скроется совет дня)
    • равный размер панелей — если мы включим разный режим отображения в каждой из панелей (древовидный и подробный), то получим проводник
  • Настройка панелей
    • автосохранение настроек панелей — будут удобно чтобы каждый раз не выбирать режим отображения панели заново
    • навигация в тиле lynx — быстрая навигация стрелками

Tips and tricks

Start from the menu

Midnight commander can be run from a menu with the correct Desktop entry. For example:

Type=Application
Version=1.0
Name=Midnight Commander
Comment=Visual file manager
Exec=mc
Icon=folder
MimeType=inode/directory
Terminal=true
Categories=Utility;

Using libtrash

Install the AUR package, and create an mc alias in the initialization file of your shell (e.g., or ):

alias mc='LD_PRELOAD=/usr/lib/libtrash.so.3.4 mc'

To apply the changes, reopen your shell session or the shell initialization file.

Default settings are defined in . You can overwrite these settings per-user in , for example:

TRASH_CAN = .Trash
INTERCEPT_RENAME = NO
IGNORE_EXTENSIONS= o;exe;com
UNCOVER_DIRS=/dev

Now files deleted by Midnight Commander (launched with mc) will be moved to the directory.

Warning:

  • With set (default), files deleted outside the home directory are moved to the trash, even if they are on a different partition. Depending on the file, this may cause a significant delay.

2 Keyboard

2.1 What does documentation mean with the C-?, M-? and F? keys?

GNU Midnight Commander documentation uses emacs style names for keyboard keys.

C stands for the Ctrl key. For example, C-f means that you should hold down the Ctrl key and press the f key.

M stands for the Meta key. Your terminal might call it Alt or Compose instead of Meta. For example, M-f means that you should hold
down the Meta/Alt/Compose? key and press the f key. If your terminal doesn’t have Meta, Alt or Compose or they don’t work you can use Esc.
For M-f press the Esc key and then press the f key.

Sometimes Ctrl and Alt are used instead of C and M for simplicity. Keep in mind that Alt can actually be Meta on some keyboards.

F? stands for a function key. If your terminal doesn’t have function keys or they don’t work you can use Esc. For example, for F3 press
the Esc key and then press the 3 key.

2.2 Why don’t function keys (or some other key) work?

Your terminfo or termcap database has missing or incorrect definitions for function keys. Type «mc -V» to see what terminal
database is being used. If the result is «using the S-Lang library with terminfo database» and you are using a very old terminfo
database, consider installing one of the enhanced terminfo files included in GNU Midnight Commander source distribution. For example,
if you are using xterm type «tic xterm.ti».

If the result is «using the S-Lang library with termcap database» you should fix your /etc/termcap database.

Up-to-date termcap and terminfo databases are available here:

  • ​http://www.catb.org/~esr/terminfo/
  • ​ftp://ftp.gnu.org/pub/gnu/ncurses/

If you don’t have permissions to edit terminal databases you can use Learn keys feature of Midnight Commander instead. Press Esc 9 o k
and follow instructions.

If all else fails you can emulate function keys by first pressing the ESC key and then one of the number keys. For example, if you want to
produce F9, press ESC, then 9. If you don’t have a ESC key on your keyboard you can try alt-9 or meta-9.

2.3 How do I use function keys F11 to F20?

These are normally mapped to function keys F1 to F10 with Shift held, e.g. function key F13 can be activated by pressing Shift-F3. You can
define the keys this way in the Options->Learn Keys dialog. The convention for PC keyboards is that F11-20 always means Shift with
F1-10.

You may find that on the Linux console with some keyboard layouts Shift-Fn is interpreted as F(n+12), not as F(n+10). This is a result
of non-uniformity of keyboard layouts. This is not an intended behavior and it may be fixed some day. In the meantime, use «Learn
Keys» to remedy this inconvenience.

2.4 Why does the ESC key behave funny?

Midnight Commander uses the ESC key as a prefix for simulating the Meta and Alt keys (for terminals which don’t have Meta or Alt, see
the three previous questions). For example, pressing ESC-a is the same as pressing Meta-a. In addition most terminals use ESC for
internal representation of arrow keys, function keys and other enhanced keys. If you want to use ESC to cancel things you have to
press it twice i.e. ESC-ESC. If you find this cumbersome you can generally use F10 to cancel. Alternatively turn on the old_esc_mode
setting in the ~/.mc/ini file. The old_esc_mode setting makes ESC work as a prefix only if another key is pressed within 0.5 seconds.
After 0.5 seconds the ESC key cancels. There is no way to make ESC cancel immediately (if we want to be able to use arrows keys and
function keys).

2.5 How can I add the plus sign (+) on the command line?

Press C-q first, then press the + sign.

The plus key is the hotkey for the select files command. If you want to add a literal plus on to the command line you must quote it by
pressing C-q first.

Another common key which needs the C-q prefix is backslash «\».

2.6 C-o doesn’t work!

Maybe C-o is a stty control character on your terminal. See man stty for details on how to list and change stty control characters.

2.7 What ‘keys’ are the «a1» and «c1» keys mentioned in the manual?

The «a1» key is the key which has the «a1» caption on it.

The «c1» key is the key which has the «c1» caption on it.

If you have to ask what these two keys are your keyboard hasn’t probably got them. Actually, I have never seen a keyboard which has
got them.

2.8 How do I change the key bindings?

There is no generic way to reconfigure the key bindings. You can use the «Learn Keys» dialog to assign keys to some actions listed in that
dialog. However, most actions cannot be redefined to use different keys.

Design

Midnight Commander is a console application with a text user interface. The main interface consists of two panels which display the file system. File selection is done using arrow keys, the insert key is used to select files and the function keys perform operations such as renaming, editing and copying files. Later versions of the Midnight Commander additionally have mouse support. Such versions are aware of GPM and X terminal emulators (such as GNOME Terminal or xterm) which support mouse reporting. When running inside an X terminal, these versions can update the name of the window in which Midnight Commander runs (if allowed by the terminal emulator).

Midnight Commander’s features include the ability to view the contents of RPM package files, to work with common archive formats as if they were simply another directory, and to function as an FTP or FISH client. Midnight Commander also includes an editor called mcedit, which can be executed as a standalone program or from Midnight Commander using the F4 key. mcedit’s features include syntax highlighting for many languages, macros, code snippets, simple integration with external tools, automatic indentation, mouse support, a clipboard and the ability to work in both ASCII and hex modes. Users also have the option to replace mcedit with the editor of their choice (Options Menu>Configuration> Use Internal Edit).

Midnight Commander can also rename groups of files, unlike a number of other file managers that can only rename one file at a time. This is convenient for manipulating large collections of files, e.g. to make them conform to a new naming convention. Midnight Commander can also move files to a different directory at the same time as it renames them. It lets the user specify the original and resulting file names using wildcard characters. This makes the power of regular expressions available for renaming files, with a convenient user interface. In addition, the user can select whether or not to use «shell patterns» or «globs» (automatic grouping of wildcards). All of these features are available by using the File > Rename/Move menu selection. (Pressing F1 would then produce a brief explanation of the options, including examples of how to use wildcards.)

Midnight Commander is based on versatile text interfaces, such as Ncurses or S-Lang, which allow it to work on a regular console, inside an X terminal, over SSH connections, over an RS-232 interface (for embedded devices) and all kinds of remote shells.

Цвета, используемые в Midnight Commander

Вид каждого элемента интерфейса определяется парой цветов: цветом текста и цветом фона. Всего доступно 16 цветов для текста и 8 цветов для фона:

+--------------------------+---------------------------+
|Цвета, используемые       |Цвета, используемые        |
|как для текста,           |только для текста          |
|так и для фона            |                           |
+===========+==============+===============+===========+
| black     | чёрный       | gray          | серый     |
+-----------+--------------+---------------+-----------+
| red       | красный      | brightred     |           |
+-----------+--------------+---------------+-----------+
| green     | зелёный      | brightgreen   |           |
+-----------+--------------+---------------+-----------+
| brown     | коричневый   | yellow        | жёлтый    |
+-----------+--------------+---------------+-----------+
| blue      | синий        | brightblue    |           |
+-----------+--------------+---------------+-----------+
| magenta   | пурпурный    | brightmagenta |           |
+-----------+--------------+---------------+-----------+
| cyan      | голубой      | brightcyan    |           |
+-----------+--------------+---------------+-----------+
| lightgray | светло-серый | white         | белый     |
+-----------+--------------+---------------+-----------+

11 More information

11.1 This document didn’t answer my question. Where else can I look for an answer?

Read messages from the Discussion (mailing list archive), visit our Documentation project or read the Manual.

Upgrade to a newer version of Midnight Commander. Many problems are fixed in the new versions.

If you still can’t find an answer, post your question to the Midnight Commander mailing list. Its address is mc@….

11.2 What mailing lists are there for Midnight Commander?

Following mailing lists discuss about Midnight Commander:

mc@…
General discussion of GNU Midnight Commander. To subscribe visit ​http://mail.gnome.org/mailman/listinfo/mc/
mc-devel@…
Technical development discussion. To subscribe visit ​http://mail.gnome.org/mailman/listinfo/mc-devel/
mc-commits@…
Mailing list only for applyed commits into master/stable branches. To subscribe visit ​http://groups.google.com/group/mc-commits/subscribe
mc-bugs@…
Mailing list only for tickets and comments (use it as RSS 🙂 ). To subscribe visit ​http://groups.google.com/group/mc-bugs/subscribe

6 Command line problems

6.2 How can I access command line history?

Meta-h shows the last commands you executed from the command line. Duplicates are suppressed from the history. Commands executed from
the subshell prompt are not shown.

You can put previous commands to the command line with Meta-p. Meta-n moves you forward in history.

Since version 4.1.15 all the input widgets have permanent history. You can summon the history listbox by pressing M-h.

6.4 I am using ksh. Can I use functions defined in the .kshrc within MC?

Sorry, MC only supports bash, tcsh and zsh functions. Ksh functions are not supported because ksh lacks the necessary hooks needed for
subshell integration.

Switch to bash or zsh. They are both quite compatible with ksh. Your ksh functions should work as such or after minimal changes.

6.5 Is there any way to include additional options or hot keys to MC?

Yes, F2 invokes an user menu, which is fully configurable. You can add any shell commands to the user menu. See the mc(1) man page for
more info.

Another way to add functionality is the external panelize feature. See the mc(1) man page for more info.

And finally, you can code any feature you want yourself. MC source code is free which means you can change it anyway you want. There
are some limitations to make sure MC stays free. See GNU General Public License for details.

6.6 When I use Ctrl-O I don’t get a subshell. How do I fix this?

Only bash, tcsh and zsh can be used as subshell. Use one of those shells as your default shell, and it will be used as subshell in GNU
Midnight Commander.

6.7 Ctrl-O doesn’t work at all. What happens?

Ctrl-O works if either the subshell is used or the terminal can save the output of the commands so it can be restored. If neither is
true, there is absolutely nothing interesting behind the panels!

Only few terminals support screen saving. It’s xterm, rxvt and other xterm-like terminals and virtual terminals on Linux and FreeBSD.

Решение проблем

Искаженное изображение

Нажмите для перерисовки интерфейса. Эта команда перерисует изображение, но не обновит список файлов в каталогах. Для обновления списка файлов на панелях используйте .

Opening files

mc uses xdg-open to open files by default, as shown in . While stderr is redirected, stdout is not, which may result in a garbled screen.

/usr/lib/mc/ext.d/*.sh
 || MC_XDG_OPEN="xdg-open"
...
open)
    "${MC_XDG_OPEN}" "${MC_EXT_FILENAME}" 2>/dev/null || \
        do_open_action "${filetype}"

Create a script to wrap xdg-open:

~/bin/xdg-open-null
#!/bin/bash
xdg-open "$@" >/dev/null

If mc is blocked until xdg-open ends, detach the process:

~/bin/xdg-open-null
#!/bin/bash
nohup xdg-open "$@" >/dev/null &

and make mc aware of it by setting the environment variable:

export MC_XDG_OPEN=~/bin/xdg-open-null

Tip: When , add before xdg-open in the script.

Find file shows no results

If the Find file dialog (accessible with ) shows no results, check the current directory for symbolic links. Find file does not follow symbolic links, so use bind mounts (see ) instead, or the External panelize command.

Общие

Вопрос 1

Почему Esc так странно себя ведёт?

Midnight Commander использует клавишу Esc как префикс для эмуляции клавиш Alt и Meta (для клавиатур, не имеющих эти клавиши). Например, нажатие клавиши ‘Esc’ и потом ‘a’ эквивалентно нажатию Alt+a (Meta+a) и т. д. Поэтому, если необходима сама Escape, нужно нажать клавишу ‘Esc’ два раза.

Можно отключить такое поведение, добавив в свой ~/.mc/ini (или в общесистемный /etc/mc/mc.ini):

    old_esc_mode = 1

В данном случае после первого нажатия клавиши ‘Esc’ на протяжении 500 миллисекунд (полсекунды) будет ожидание нажатия другой клавиши (полсекунды клавиша Esc будет считаться как Meta). По истечении этого времени клавиша Esc отработает как двойное нажатие.

Чтобы уменьшить время ожидания другой клавиши, используйте переменную окружения ‘KEYBOARD_KEY_TIMEOUT_US’. Значение переменной указывается в микросекундах. Например, чтобы MC отработал нажатие клавиши ESC с задержкой в 25 миллисекунд, пропишите в ~/.bashrc:

export KEYBOARD_KEY_TIMEOUT_US=25000

Начиная с версии 4.7.3, эта настройка доступна через конфигурационный диалог «Параметры конфигурации» (меню «Настройки» -> «Конфигурация…»).

Вопрос 2

Как запустить mc с интерфейсом на другом языке(кодировке) ?

Вводим в командной строке «LANG=en_EN.UTF-8 mc» (английский), «LANG=ru_RU.UTF-8 mc» (русский UTF-8), «LANG=ru_RU.KOI8-R mc» (русский KOI8-R), «LANG=it_IT.UTF-8 mc» (итальянский UTF-8) и тд.

Советы и рекомендации

Переназначение сочетаний клавиш

Создайте копию стандартных комбинаций клавиш для текущего пользователя:

cp /etc/mc/mc.keymap ~/.config/mc/

и отредактируйте файл под свои нужды. Вы можете использовать также другие файлы .keymap. Например, можно установить при помощи переменной окружения :

export MC_KEYMAP=/etc/mc/mc.emacs.keymap

Навигация стрелками

Чтобы иметь возможность навигации по каталогам с помощью клавиш со стрелками как в Lynx, перейдите в меню Options (, ) > Panel Options () и установите флажок Lynx-like motion в группе Navigation (), затем нажмите OK ().

Запуск из меню

Midnight Commander можно запускать из меню, создав файл desktop entry. Пример:

Type=Application
Version=1.0
Name=Midnight Commander
Comment=Visual file manager
Exec=mc
Icon=folder
MimeType=inode/directory
Terminal=true
Categories=Utility;

Использование libtrash

Библиотека libtrash перехватывает вызовы функций удаления файлов и вместо удаления выполняет перемещение файлов в корзину.

Установите AUR из AUR и создайте псевдоним для mc в файле инициализации вашей командной оболочки (например, или ):

alias mc='LD_PRELOAD=/usr/lib/libtrash.so.3.3 mc'

Чтобы изменения вступили в силу, переоткройте сеанс терминала или просто выполните скрипт инициализации командой source.

Стандартные настройки библиотеки находятся в файле . Вы можете переопределить их для текущего пользователя, создав пользовательский файл настроек , например:

TRASH_CAN = .Trash
INTERCEPT_RENAME = NO
IGNORE_EXTENSIONS= o;exe;com

Теперь, после запуска mc, удаляемые файлы будут попадать в каталог корзины .

Важно:

  • С установленной опцией (значение по умолчанию), файлы вне домашнего каталога будут попадать в корзину, даже если они находятся на другом разделе диска. Такие файлы фактически перемещаются копированием и удалением из исходного расположения, поэтому процедура удаления в корзину файла на другом разделе может занимать продолжительное время.

Доступ в шелл

  • вы можете вводить любую команду — просто начинаете печатать и она появляется внизу в маленьком приглашении ввода вашего шелла. Нажатие на запустит ее на исполнение.
  • не пытайтесь нажать в попытках вызвать автодополнение — вы просто смените текущую панель. Чтобы вызвать автодополнение надо нажать последовательность . Тут все как в обычном шелле — первый раз оно пытается дополнить максимально возможную часть команды, а повторное нажатие последовательности показывает ве возможные варианты (да еще и с выбором как в zsh).
  • а если надо показать большой терминал? На надо выходить из mc — нажимаете и панели файловый менеджер скрывается оставляя вас наедине с консолью. Чтобы его вернуть заново нажимает .
  • — копирует имя текущего выбранного файла в строку терминала (удобно для передачи имени каким-нибудь командам)
Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector