Руководство по русской локализации Gentoo Linux

Вопросы установки, настройки. использования ОС Linux
Ответить
Аватара пользователя
icedog
Site Admin
Сообщения: 229
Зарегистрирован: Пн авг 03, 2020 5:49 pm
Откуда: Краснодар
Контактная информация:

Руководство по русской локализации Gentoo Linux

Сообщение icedog »

Руководство по русской локализации Gentoo Linux (Архив)
Алексей Федорчук автор

Обновлено 19 февраля 2003
Исходный документ обновлен 19 июня 2006

1. Введение

Что такое русская локализация

В понятие локализации входит обеспечение вывода и ввода символов национальных языков (в случае использования набора символов, отличных от чистого латинского) и определение переменных окружения, зависящих от страны, языка и набора символов (то есть собственно установка locale). В число таких переменных, кроме страны, языка и набора символов, входят также представление даты и времени, разделителей десятичных дробей, денежных единиц и так далее.

Вследствие различия подходов в этом документе будут отдельно рассмотрены локализация текстового (то есть Linux-консоли) и графического (оконной системы X) режимов.

О кириллических кодировках

В условиях России и некоторых других стран бывшего СССР локализация осложняется множественностью наборов символов (charsets), используемых для представления алфавитов, основанных на кириллице. Причём для Unix-систем получили распространение минимум три таких набора, в просторечии именуемых кодировками: традиционная для свободных Unix-клонов (в том числе и Linux) кодировка KOI8-R, кодировка ISO-8859-5 (именуемая кодировкой ГОСТ), используемая в проприетарных Unix-системах, и кодировка CP1251 (или кодировка Windows). Кроме того, для обеспечения экранного вывода используется кодировка CP866 (или кодировка DOS). Наконец, в последнее время всё большую популярность получает кодировка UTF-8.

В Gentoo Linux штатно (как говорится, из коробки) поддерживается кодировка KOI8-R, и всё сказанное ниже относится именно к ней. Локализацию для кодировок ISO-8859-5 или CP1251 пользователь может выполнить самостоятельно, получив из независимых источников некоторые дополнительные компоненты. О локализации для кодировки UTF-8, призванной унифицировать подход к интернационализации, будет говориться в следующих версиях этого документа, когда использование её станет общепринятым.

2. Базовая кириллизация консоли

Введение

Итак, базовая локализация консоли включает обеспечение вывода национальных символов на экран и ввода их с клавиатуры. Однако в случае кириллической локализации вследствие особенностей наборов символов и аппаратных особенностей PC для ввода и для вывода используются, как правило, разные кодировки. И это требует еще двух дополнительных шагов — установки карты соответствия между наборами символов ввода и вывода, и активизация её на каждой из виртуальных консолей.

Установка экранного шрифта

Экранный шрифт, загружаемый по умолчанию при старте системы, определяется в файле /etc/rc.conf строкой

Листинг 2.1: Строка, определяющая экранный шрифт

Код: Выделить всё

CONSOLEFONT="default8x16"
Для вывода русских букв "умолчальное" значение следует заменить на имя какого-либо файла шрифта с поддержкой кириллицы, например, cp866-8x16 для представления кодировки DOS или koi8r-8x16 — для кодировки KOI8-R. Например,

Листинг 2.2: Определение экранного шрифта для кодировки cp866

Код: Выделить всё

CONSOLEFONT="cp866-8x16"
Или —

Листинг 2.3: Определение экранного шрифта для кодировки KOI8-R

Код: Выделить всё

CONSOLEFONT="koi8r-8x16"
Примечание: Файлы шрифтов (и не только кириллических) находятся в каталоге /usr/share/consolefonts/ и имеют вид *.gz, *.psf.gz или *.psfu.gz. При стандартном их размещении и форме ни полного пути, ни "расширения" имени указывать не обязательно.

Важно: В кириллическом Linux'е для экранного вывода, как правило, используется кодировка cp866 (вне зависимости от того, какой набор символов принят для клавиатурного ввода). О причинах этого говорить можно было бы долго — достаточно указать, что в любом ином случае программы, использующие псевдографику (например, Midnight Commander) приобретут весьма уродливый вид.

Экранные кириллические шрифты, поставляемые с Gentoo Linux, далеки от эстетического совершенства (справедливости ради заметим, что это относится почти ко всем Unix-клонам). И потому в качестве источника дополнительных шрифтов можно рекомендовать пакет console-tools-cyrillic Виктора Вагнера. В результате приведенная выше в качестве примера строка может принять вид вроде

Листинг 2.4: Один из лучших кириллических шрифтов для консоли

Код: Выделить всё

CONSOLEFONT="UniCyr-sans"
Установка раскладки клавиатуры

Загружаемая по умолчанию раскладка клавиатуры также определяется в файле /etc/rc.conf строкой

Листинг 2.5: Строка, определяющая раскладку клавиатуры

Код: Выделить всё

KEYMAP="us"
По аналогии с предыдущим случаем легко догадаться, что значение us следует заменить на имя файла какой-либо кириллической (на этот раз уже в кодировке KOI8-R) раскладки. Место этих файлов (имеющих вид *.map.gz) — в каталоге /usr/share/keymaps/i386/qwerty, где для русской кодировки KOI8-R имеется несколько раскладок, например, ru1-ru4. Различия между ними — в соответствии различной маркировке клавиш (DOS или Windows — не путать с одноименными кодировками) и положении переключателя латиница/кириллица. Рискну взять на себя смелость рекомендовать раскладку ru4 — для Windows-маркированных клавиатур, в которой переключателем служит CapsLock (при этом фиксация верхнего регистра обеспечивается одновременным нажатием клавиш Shift+CapsLock). То есть строка примет вид:

Листинг 2.6: Один из примеров определения кириллической раскладки

Код: Выделить всё

KEYMAP="ru4"
Примечание: Как и в случае с экранными шрифтами, при стандартном расположении файлов раскладок указывать полный путь к ним и "расширение" имени нет необходимости.

Предупреждение: При желании вы можете выбрать и раскладку клавиатуры для кодировки cp1251 (например, ru_win). Однако в этом случае придётся отыскать или самостоятельно изготовить таблицу перекодировки (mapscreen) cp1251->cp866.

Примечание: Нет ничего более уродливого, чем программы, использующие псевдографику, при экранном представлении в кодировке cp1251.

Установка карты соответствия (mapscreen)

Теперь остаётся только обеспечить соответствие между кодировками ввода (KOI8-R) и вывода (cp866), то есть загрузить соответствующую таблицу перекодировки (mapscreen). Для этого снова обращаемся к файлу /etc/rc.conf. Строка в нём, отвечающая за эту операцию, имеет по умолчанию такой вид:

Листинг 2.7: Строка, определяющая раскладку клавиатуры

Код: Выделить всё

#CONSOLETRANSLATION="cp437_to_iso01"
Необходимо, сняв с неё символ комментария (#), заменить "умолчальное" значение на необходимое нам, и подсмотреть его можно в каталоге /usr/share/consoletrans — это koi2alt:

Листинг 2.8: Установка таблицы соответствия cp866->KOI8-R

Код: Выделить всё

CONSOLETRANSLATION="koi2alt"
Предупреждение: Пожалуйста, не забудьте снять символ комментария со строки CONSOLETRANSLATION — кто только на моей памяти не наступал на эти грабли :-)

Примечание: Если вы по каким-либо причинам остановились на представлении экранных шрифтов в кодировке KOI8-R, загрузка и активизация карты соответствия, разумеется, не нужна.

Активизация карты соответствия

Результатом выполненной операции будет то, что после перезагрузки машины мы получили бы нормальный вывод кириллического текста (записанного в кодировке KOI8-R), но только — на первой (т.н. системной) консоли. Чтобы иметь то же самое на остальных виртуальных консолях (а в Gentoo Linux их по умолчанию еще 5), та же карта соответствия должна быть активизирована на каждой из них с помощью направления Escape-последовательности \033(K (символ \ в данном случае показывает, что следующие за ним символы рассматриваются как специальные). Достигнуть этого можно разными способами. Например, создать в каталоге /etc/init.d/ файл consoletrans и в любом текстовом редакторе внести в него следующие строки:

Листинг 2.9: Сценарий активизации mapscreen

Код: Выделить всё

for i in 1 2 3 4 5 6; do
echo -ne '\033(K' > /dev/vc/$i
done
Примечание: Это — для случая 6-ти консолей по умолчанию. Если количество их изменялось пользователем, значения in, очевидно, должны быть приведены в соответствие с реальностью.

Примечание: Следует отметить, что начиная с baselayout-1.8.x необходимость в этом отпала, поскольку этот код был встроен в /etc/init.d/consolefont.

Теперь командой chmod a+x /etc/init.d/consoletrans созданному скрипту следует присвоить бит исполнения, после чего он добавляется к уровню исполнения по умолчанию (default runlevel):

Листинг 2.10: Сценарий активизации mapscreen

Код: Выделить всё

# rc-update add consoletrans default
Примечание: Механизм автоматического обновления стартовых скриптов подробно описан в соответствующем разделе документации.

Вот теперь после перезагрузки машины мы получим полноценно локализованную консоль.

Примечание: Все действия, описанные в данной главе, могут быть выполнены как на заключительных шагах (final steps) установки Gentoo Linux, так и в произвольный момент времени в дальнейшем.

3. Установка русской locale

Установка locale ru_RU.KOI8-R

Установить локально-зависимые переменные можно различными способами, в том числе и просто в профильных файлах отдельных пользователей. Однако в Gentoo Linux предусмотрен автоматический механизм установки любых переменных окружения в качестве общесистемных — env-update, подробно описанный в соответствующих разделах документации.

Для использования этого механизма следует в файл /etc/env.d/02locale добавить строку

Листинг 3.1: Установка переменной LANG

Код: Выделить всё

LANG="ru_RU.KOI8-R"
которая определяет не только язык locale, но и все остальные локально-зависимые переменные. Далее выполняем команду env-update, дополняющую глобальный профильный файл /etc/profile, после чего остаётся только перечитать последний командой source /etc/profile. Теперь в ответ на команду locale последует вывод

Листинг 3.2: Вывод команды locale после установки переменной LANG

Код: Выделить всё

LANG=ru_RU.KOI8-R
LC_CTYPE="ru_RU.KOI8-R"
LC_NUMERIC="ru_RU.KOI8-R"
LC_TIME="ru_RU.KOI8-R"
LC_COLLATE="ru_RU.KOI8-R"
LC_MONETARY="ru_RU.KOI8-R"
LC_MESSAGES="ru_RU.KOI8-R"
LC_PAPER="ru_RU.KOI8-R"
LC_NAME="ru_RU.KOI8-R"
LC_ADDRESS="ru_RU.KOI8-R"
LC_TELEPHONE="ru_RU.KOI8-R"
LC_MEASUREMENT="ru_RU.KOI8-R"
LC_IDENTIFICATION="ru_RU.KOI8-R"
LC_ALL=
свидетельствующий, что все локально зависимые переменные приняли значения для страны России (ru), русского языка (_RU) и набора символов KOI8-R. Те же значения этих переменных будут устанавливаться и в сеансах всех пользователей, вошедших в систему после выполнения команды env-update.

Предупреждение: Механизм env-update однозначно работает в том случае, если пользовательской оболочкой (login shell) является /bin/bash. При использовании иных командных оболочек могут потребоваться некоторые дополнительные действия. Например, если в качестве login shell выступает оболочка zsh, следует отказаться от создания файла ~/.zshenv в домашнем каталоге пользователя.

Важно: Переменная LANG=ru_RU.KOI8-R должна быть установлена в любом случае, даже если вы не любите сообщений на русском языке: в противном случае во многих программах (в том числе для XFree86) окажется просто невозможным, например, ввод символов кириллицы.

Как уже сказано, установка переменной LANG автоматически определяет и все прочие локально-зависимые переменные. Что в ряде случаев может быть нежелательным. Например, некоторые программы расчетного характера требуют, чтобы в качестве десятичного разделителя использовался символ точки, как в locale POSIX, а не запятой, как это принято в locale ru_*. Чтобы добиться этого, достаточно в конец файла /etc/env.d/02locale, после определения LANG, добавить строку вида:

Листинг 3.3: Установка переменной LC_NUMERIC

Код: Выделить всё

LC_NUMERIC="POSIX"
Аналогичным образом могут поступить пользователи, испытывающие стойкую неприязнь к русскоязычным меню и сообщениям программ:

Листинг 3.4: Установка переменной LC_NUMERIC

Код: Выделить всё

LC_MESSAGES="POSIX"
4. Установка часового пояса

Системные часы по Гринвичу

Если системные часы машины в BIOS Setup установлены на время по Гринвичу (UTC), для настройки часового пояса достаточно создать символическую ссылку /etc/localtime на файл, описывающий данный часовой пояс. Например, для установки московского времени это будет выглядеть так:

Листинг 4.1: Установка московского времени

Код: Выделить всё

ln -sf /usr/share/zoneinfo/Europe/Moscow /etc/localtime
Примечание: Точное обозначение часовых поясов для России можно посмотреть в каталогах /usr/share/zoneinfo/Europe (имеет силу также для Украины и Белоруссии) и /usr/share/zoneinfo/Asia (для азиатской части России). Например, пользователям из Петропавловска-Камчатского указанная команда потребуется в следующем виде:

Листинг 4.2: Установка времени для Петропавловска-Камчатского

Код: Выделить всё

ln -sf /usr/share/zoneinfo/Asia/Kamchatka /etc/localtime
Системные часы по местному времени

Если системные часы данной машины установлены по местному времени, кроме создания указанной ссылки потребуется внести еще и изменения в файл /etc/rc.conf, а именно: строку CLOCK="UTC" заменить на CLOCK="local".

5. Локализация оконной системы X

Введение

Локализация оконной системы X (конкретно — её свободной реализации XFree86) может быть выполнена двумя путями: с помощью специальных утилит конфигурирования (обычно — xf86config, используемой для настройки графического режима вообще) или прямым редактированием конфигурационного файла /etc/X11/XF86Config.

Локализация с использованием утилиты xf86config

Утилита xf86config в большинстве случаев позволяет корректно выполнить кириллизацию системы XFree86 уже на стадии начальной её настройки. Для этого необходимо дать (в консольном режиме) одноименную команду и правильно ответить на вопросы, относящиеся к определению языково-зависимых параметров, и следующие после указания выбора типа клавиатуры.

Первый из таких вопросов — выбор страны (Enter a number to choose the country), ответ на который, на самом деле, определяет базовую раскладку клавиатуры. Очевидными ответами являются 8 Belarusian для Белоруссии и 70 Ukrainian для Украины, тогда как для России предлагается два варианта: 53 Russian и 54 Russian (cyrillic phonetic). Первый — это традиционная раскладка qwerty, второй же — фонетическая раскладка ywerti, в которой символы кириллицы расположены на месте созвучных латинских. Она использовалась на старых терминалах и ныне практически не встречается. Так что на самом деле и тут выбор 53 Russian практически однозначен.

Далее следует предложение указать вариант русской раскладки (Please enter a variant name for 'ru' layout). Если, просто нажав Enter, отказаться от этого, будет установлен так называемый DOS-вариант раскладки (вернее, маркировки клавиш); маркированные таким образом клавиатуры практически вышли из употребления, поэтому следует, введя winkeys, выбрать Windows-вариант (не следует путать его с Windows-кодировкой, иначе говоря — cp1251).

Затем, введя y, следует положительно ответить на вопрос об указании дополнительных опций расширения XKB (Do you want to select additional XKB options (group switcher, group indicator, etc.)?): это позволит определить переключатель латиница/кириллица (в силу исторических причин русская раскладка клавиатуры в XFree86 по умолчанию такового не имеет вообще).

В результате следующим шагом будет предложение выбрать клавишу или клавишную комбинацию для такого переключателя. Возможные варианты включают:

Листинг 5.1: Варианты выбора переключателя латиница/кириллица

Код: Выделить всё

  1  R-Alt switches group while pressed                
  2  Left Win-key switches group while pressed         
  3  Right Win-key switches group while pressed        
  4  Both Win-keys switch group while pressed          
  5  Right Alt key changes group                       
  6  Caps Lock key changes group                       
  7  Menu key changes group                            
  8  Left Win-key changes group                        
  9  Right Win-key changes group                       
 10  Both Shift keys together change group             
 11  Control+Shift changes group                       
 12  Alt+Control changes group                         
 13  Alt+Shift changes group   


Из них следует выбирать, руководствуясь своими предпочтениями. Однако по вполне понятным причинам можно рекомендовать, чтобы переключатель раскладок был идентичен для текстового (консольного) и графического режимов. ИМХО, лучше всего на эту роль подходит клавиша CapsLock (для этого в консоли должна быть установлена раскладка ru4). При этом первичная функция этой клавиши (фиксация верхнего регистра), как и в консоли, будет выполняться одновременным нажатием Shift+CapsLock

Примечание: Не менее удобным представляется и использование в качестве переключателя какой-либо из т.н. Windows-клавиш, имеющихся на всех современных клавиатурах. Однако при этом для достижения идентичности переключения в консоли и в XFree86 потребуются расширенные раскладки клавиатуры из упомянутого выше пакета console-tools-cyrillic.

Следующие несколько вопросов позволяют указать переключатель для третьей клавиатурной раскладки, дополнительные позиции управляющей клавиши Control, индикацию текущей раскладки (например, индикаторами CapsLock или ScrollLock) и ещё некоторые опции. Если в них нет необходимости — ответы на эти вопросы можно просто пропустить, нажимая клавишу Enter.

Покончив с настройкой клавиатуры, следует завершить конфигурирование XFree86 (включая настройку видеорежимов) и выйти из программы xf86config с сохранением результатов в файле /etc/X11/XF86Config.

Установка кириллических шрифтов

Программа xf86config обеспечивает настройку клавиатурного ввода, но не подключает по умолчанию шрифтов с символами кириллицы — это достигается редактированием файла /etc/X11/XF86Config. Его следует открыть в любом текстовом редакторе и отыскать в Section "Files" описание путей к шрифтовым файлам.

Предупреждение: При вызове файла /etc/X11/XF86Config необходимо отключить режим переноса строк в используемом редакторе.

Пути к файлам шрифтов описываются следующим образом:

Листинг 5.2: Описание путей к файлам шрифтов

Код: Выделить всё

FontPath   "/usr/X11R6/lib/X11/fonts/local/"
FontPath   "/usr/X11R6/lib/X11/fonts/misc/"
FontPath   "/usr/X11R6/lib/X11/fonts/75dpi/:unscaled"
FontPath   "/usr/X11R6/lib/X11/fonts/100dpi/:unscaled"
FontPath   "/usr/X11R6/lib/X11/fonts/Type1/"
FontPath   "/usr/X11R6/lib/X11/fonts/Speedo/"
FontPath   "/usr/X11R6/lib/X11/fonts/75dpi/"
FontPath   "/usr/X11R6/lib/X11/fonts/100dpi/"
В этот список следует внести путь к файлам шрифтов с поддержкой кириллицы. По умолчанию в любой современной версии XFree86 имеется один набор кириллических шрифтов — Cronyx, расположенный в каталоге /usr/X11R6/lib/X11/fonts/cyrillic/. И потому первая строка указанной секции должна принять вид

Листинг 5.3: Описание пути к файлам кириллических шрифтов

Код: Выделить всё

FontPath   "/usr/X11R6/lib/X11/fonts/cyrillic/"
Важно: Строка с кириллическими шрифтами должна быть первой в списке путей, дабы именно они обнаруживались бы любыми программами в первую очередь при совпадении их имен или псевдонимов с таковыми шрифтов, не имеющих символов кириллицы.

Примечание: Шрифты производства Cronyx содержат ограниченное число гарнитур. Кроме того, они являются растровыми и вообще далеки от эстетического совершенства. Поэтому их по возможности лучше дополнить (или заменить) шрифтами от независимых производителей. В качестве таковых можно рекомендовать коллекцию масштабируемых (TTF и ATM) лицензионно чистых шрифтов Валентина Филиппова, входящих в российскую сборку OpenOffice и в последние версии дистрибутивов Altlinux.

Ручная настройка клавиатуры для ввода кириллицы

К кириллизации XFree86 посредством программы xf86config целесообразно прибегать только при начальной настройке этой системы. Если же в ходе использования Gentoo Linux возникнет необходимость дополнительного конфигурирования (например, изменения положения переключателя раскладок), проще обратиться к прямому редактированию файла /etc/X11/XF86Config.

За настройку клавиатуры в нём отвечает Section "InputDevice". В ней, после указания идентификатора клавиатуры (а оконная система X в состоянии поддерживать, даже на локальной машине, более одной физической клавиатуры) и её драйвера, следует описание т.н. правил (rules), определяющих раскладку клавиатуры. Оно имеет вид вроде следующего:

Листинг 5.4: Описание раскладки клавиатуры

Код: Выделить всё

Option "XkbRules"   "xfree86"
Option "XkbModel"   "pc105"
Option "XkbLayout"  "ru"
Option "XkbVariant" "winkeys"
Option "XkbOptions" "grp:caps_toggle,grp_led:caps"
Здесь, разумеется, можно изменить всё, что угодно. Однако практически имеет смысл рассмотреть только возможные варианты значений для строки Option "XkbOptions". Значение, приведенное в примере, соответствует переключателю раскладок CapsLock (grp:caps_toggle) и индикатору Capslock как показателю включения русской раскладки (grp_led:caps). И то, и другое можно изменить, если не устраивает. Доступные значения содержатся (вместе с их краткими описаниями) в секции ! option файла /usr/X11R6/lib/X11/xkb/rules/xfree86.lst.

Примечание: Описание раскладок клавиатуры через набор правил — лишь одно из возможных. О других способах сделать это можно прочитать на http://www.tsu.ru/~pascal/other/xkb.
Сборка, настройка, ремонт серверов в Краснодарском крае. 1С Бухгалтерия. Обновления 1С. Сервер под 1С. Аренда+Написать в WhatsApp+
Аватара пользователя
icedog
Site Admin
Сообщения: 229
Зарегистрирован: Пн авг 03, 2020 5:49 pm
Откуда: Краснодар
Контактная информация:

Re: Руководство по русской локализации Gentoo Linux

Сообщение icedog »

HOWTO Create an UTF-8 enabled system (Архив)

From Gentoo Linux Wiki
Jump to: navigation, search
This article is part of the HOWTO series.

Contents


* 1 WARNING
* 2 Summary
* 3 Preparing the locales
* 4 Setting up locales


WARNING

This article is OUT OF DATE.
Newer versions of glibc will warn you about the use of /etc/locales.build and to use /etc/locale.def instead, this article needs to be reviewed and rewritten for newer versions of glibc (or perhaps notes need to be made for new and old versions).

FYI Maintainers: I'm duely sorry for this edit, but I don't know how to look for relevant stubs and don't see any articles with an incomplete stub. Feel free to edit a stub in and send me a message on User_talk:VxJasonxV!!

Summary

There are many reasons to build a UTF-8-enabled system. Perhaps reason enough is that UTF-8 is the encoding of the future -- everybody is switching to UTF-8, and for good reason: with UTF-8, it's possible to represent truly every language in the world in a single charset. Operating systems are beginning to standardize on UTF-8 -- all versions of Mac OS X use UTF-8 internally, for example. To compatibly share text files with Mac OS X, you need to be using UTF-8, and we expect other operating systems to follow suit.

English-speaking users may not immediately see the benefit of UTF-8, as they may think they have no need for the vast array of special characters UTF-8 offers. But in most every other language, special characters are used frequently. And in today's highly international world, you may very well want to be able to represent, say, a Japanese word -- a song title, perhaps, or the name of a television show or movie. Or maybe you'd like for a person whose name contains non-Latin characters -- perhaps a Polish or Russian name -- to be able to represent their name properly. Just a thought. Even those using purely the English language will benefit from switching to UTF-8, since with it you can represent many additional wonderful and useful typographical symbols that are not available in the ASCII or ISO-8859-1 charsets.

Preparing the locales

As first step, you must know exactly which locales you need to use. The locales can be found at /usr/share/i18n/locales. Usually, the locale is the code of the language (for example it), followed by an underscore (_) and by the capital code of the country (IT). In my example it is it_IT. For European countries which uses new euro currency, the @euro string must be appended to the locale ID. If I don't say it explicitly, when I say locale ID, I intend the one without the euro specification.

When you know which locale you must use, then edit /etc/locales.build and add the locales you need. My recommendation is to maintain always the en_US locale, as some programs don't work without it.
File: /etc/locales.build

Код: Выделить всё

en_US/UTF-8
it_IT/UTF-8
it_IT@euro/UTF-8
As you can see, the locale itself is not enough. The complete syntax is locale/charset. As our charset is UTF-8, you should always use UTF-8 as charset. Simple.

For European countries which use euro currency, you should add two different locales, first the one without the euro specification, and then the one with it. We'll see later why we should do this.

At this point you can add userlocales USE flag to global flags (or to sys-libs/glibc specific flags), and emerge glibc.

Setting up locales

Now you should create /etc/env.d/02locale file, specifying the locales to use. You can add one or two different values usually, but for european countries with euro currency you need to add a third.

Код: Выделить всё

LANG=it_IT.UTF-8
LC_ALL=it_IT.UTF-8
In this case the language is set as for the locales (numeric values, currencies, and so on) to the Italian one. I usually use English as my interface language, so in this case you should change the file to something like this:

Код: Выделить всё

LANG=en_US.UTF-8
LC_ALL=it_IT.UTF-8
Please note that you must use the same charset encoding for LANG and LC_* values.

For European countries with euro currency, you must change this. Theoretically you should use something like it_IT.UTF-8@euro, but doing this makes X complain. To workaround this, you can use this:

Код: Выделить всё

LANG=it_IT.UTF-8
LC_MONETARY=it_IT.UTF-8@euro
You can't use LC_ALL, because it will overwrite LC_MONETARY, no matter if LC_MONETARY is specified after or before LC_ALL. But some programs complain (see [1]) if LC_ALL isn't set.

This way you use the added euro support only for monetary data, which is what was changed, and X will not complain because is unable to find out the locale.

If your UTF-8 locale of choice is not available, you can create it with the following command. Replace en_GB with your locale of choice:

Код: Выделить всё

localedef -c -i en_GB -f UTF-8 en_GB.UTF-8
Now you should run env-update && source /etc/profile, or restart the system (or logout-login and restart every service in the system), and you'll be using UTF-8 for everything.
Аватара пользователя
icedog
Site Admin
Сообщения: 229
Зарегистрирован: Пн авг 03, 2020 5:49 pm
Откуда: Краснодар
Контактная информация:

Re: Руководство по русской локализации Gentoo Linux

Сообщение icedog »

TIP Specifying only needed locales (Архив)
From Gentoo Linux Wiki
Jump to: navigation, search
This article is part of the Tips & Tricks series.


The locales a user can choose from are built by the glibc. Usually all available locales starting from aa_DJ (Afar locale for Djibouti) over en_US (English locale for the USA) to zu_ZA.utf8 (Zulu locale for South Africa) will be installed. Unless you're working at the UN and administer a central server for all member states, it is difficult to conceive why you would need a system where all of these locales are installed. This week's tip was written with all those of you in mind who'd like to save 90 percent of the space occupied by locales in their system, by limiting the number of installed locales to the bare minimum.

Ever since sys-libs/glibc-2.3.4.20040619-r2 has been in Portage, a USE-flag called userlocales was provided to make sure only those locales mentioned in /etc/locales.build are to be built and installed. As a side-effect, this also leads to a much faster emerge of glibc, obviously.


Code: Activate the userlocales USE flag especially for glibc

Код: Выделить всё

echo "sys-libs/glibc userlocales" >> /etc/portage/package.use
Now specify the locales you want to be able to use:


File: nano -w /etc/locales.build

Код: Выделить всё

#The format of the locales is described in the file itself.
en_US/ISO-8859-1
en_US.UTF-8/UTF-8
de_DE/ISO-8859-1
de_DE@euro/ISO-8859-15
de_DE.UTF-8/UTF-8
The entries in the file are, like the header of the file suggests, in the format <locale>/<charmap>. <locale> is a locale from the /usr/share/i18n/locales directory and <charmap> is the name of one of the files in /usr/share/i18n/charmaps/.

For further information about locale-handling make sure you read our Gentoo Linux Localization Guide.

Another interesting tool is app-admin/localepurge which can clean out any installed man-page or info-file in languages you don't need on your system. You should read the man-page to localepurge in any case, and configure languages you intend to keep in /etc/locale.nopurge.

By the way, if you want to prohibit the installation of all man-pages, info-files or documentation, for example when space on your disk is severely limited, you can add noman, nodoc and/or noinfo to FEATURES in your /etc/make.conf.

This tip was reprinted with permission from Gentoo Weekly Newsletter: November 8, 2004

--SmokesLikeaPoet 01:48, 12 Nov 2004 (GMT)
Аватара пользователя
icedog
Site Admin
Сообщения: 229
Зарегистрирован: Пн авг 03, 2020 5:49 pm
Откуда: Краснодар
Контактная информация:

Re: Руководство по русской локализации Gentoo Linux

Сообщение icedog »

Создание только нужных вариантов locale (Архив)
Материал из Gentoo Linux Wiki.

Локали, которые пользователь может использовать, собираются пакетом sys-libs/glibc. Обычно устанавливаются все доступные локали: от aa_DJ (локаль Afar для Djibouti) до zu_ZA.utf8 (локаль Zulu для Серверной Африки).

Но ведь зачастую не требуется такое количество локалей, если вы не администратор мультинационального сервера, конечно. :) Этот совет поможет вам установить только необходимые вам локали.

С тех пор, как в портеджах есть пакет sys-libs/glibc-2.3.4.20040619-r2 , существует флаг под названием userlocales, который служит для того, чтобы указать портеджам те локали, которые необходимо установить. Это также сказывается на скорости установки glibc (замечали, наверное, что локали собираются довольно долго...)

Следующая строчка активирует флаг userlocales для glibc:

Код: Выделить всё

echo "sys-libs/glibc userlocales" >> /etc/portage/package.use
Теперь укажите локали, которые вы хотите устанавливать:

File: /etc/locales.build

Код: Выделить всё

en_US/ISO-8859-1
en_US.UTF-8/UTF-8
ru_RU.UTF-8/UTF-8
ru_RU.KOI8-R/KOI8-R
Формат строк такой: локаль/кодировка

Список всех доступных локалей и кодировок можно посмотреть в папке /usr/share/i18n.

Для дополнительной информации об управлении локалями почитайте наш Gentoo Linux Localization Guide

Между прочим, если вы хотите запретить установку любых man-страниц, info-файлов или документации (к примеру, для экономии дискового пространства), вы можете добавить noman, nodoc и/или noinfo в переменную FEATURES в /etc/make.conf
Аватара пользователя
icedog
Site Admin
Сообщения: 229
Зарегистрирован: Пн авг 03, 2020 5:49 pm
Откуда: Краснодар
Контактная информация:

Re: Руководство по русской локализации Gentoo Linux

Сообщение icedog »

HOWTO Make your system use unicode/utf-8 (Архив)
From Gentoo Linux Wiki

This article is part of the HOWTO series.

Contents


* 1 Why Unicode?
* 2 Kernel Stuff
o 2.1 Kernel Bugs
* 3 Installing locales
o 3.1 For glibc versions 2.3.6-r4 and later
o 3.2 Earlier versions
* 4 Console setup
* 5 Apps
o 5.1 Terminal emulators
+ 5.1.1 xterm
+ 5.1.2 urxvt
+ 5.1.3 GNU Screen
o 5.2 Editors
+ 5.2.1 Vim
+ 5.2.2 Nano
o 5.3 Editing
+ 5.3.1 LaTeX
o 5.4 Mail
+ 5.4.1 mutt
o 5.5 Shells
+ 5.5.1 bash
+ 5.5.2 zs P + 5.5.3 mc
o 5.6 X
+ 5.6.1 fluxbox
+ 5.6.2 OpenOffice.org
o 5.7 Sound
+ 5.7.1 Xmms
# 5.7.1.1 Easy method
# 5.7.1.2 GTK 1.x method
* 6 Converting an Old System
o 6.1 Converting Plain Text Files
o 6.2 Converting Filenames
* 7 Links


Why Unicode?

From What is Unicode? at www.unicode.org:

Fundamentally, computers just deal with numbers. They store letters and other characters by assigning a number for each one. Before Unicode was invented, there were hundreds of different encoding systems for assigning these numbers. No single encoding could contain enough characters: for example, the European Union alone requires several different encodings to cover all its languages. Even for a single language like English no single encoding was adequate for all the letters, punctuation, and technical symbols in common use.

These encoding systems also conflict with one another. That is, two encodings can use the same number for two different characters, or use different numbers for the same character. Any given computer (especially servers) needs to support many different encodings; yet whenever data is passed between different encodings or platforms, that data always runs the risk of corruption.

Unicode is changing all that!

Unicode provides a unique number for every character, no matter what the platform, no matter what the program, no matter what the language.

It should be noted that the above text is slightly ambiguous. To clarify: Unicode is a number<->character mapping definition but it is not an encoding. The actual encoding of the numbers into bits comes in several flavours including UTF-8, UTF-EBCDIC, UTF-16, UTF-16BE, UTF-16LE, UTF-32, UTF-32BE, UTF-32LE, UCS-2, and UCS-4, so saying that unicode obsoletes encoding worries is an overstatement. These encodings do not conflict with each other, however.

Kernel Stuff

To activate unicode in the kernel set the following in:


Linux Kernel Configuration: Unicode support

Код: Выделить всё

File systems --->
 Native Language Support --->
   (utf8) Default NLS Option
   <*>   NLS UTF8
Now your filenames will be encoded in utf8 per default, after you re-compile your kernel.

If you compiled it as a module, be sure to load it:

Код: Выделить всё

modprobe nls_utf8
To avoid doing this every time you boot, add "nls_utf8" to your /etc/modules.autoload.d/kernel-2.6 or -2.4 file.

Kernel Bugs

Please note that there exists a bug in some Linux kernel versions which affects UTF-8 locales using dead keys. The issue has reportedly been solved since kernel version 2.6.11.

Installing locales

The system locales come with the glibc package. By default almost all possible locales are installed, though you can choose to install only the locales you need.

For glibc versions 2.3.6-r4 and later

Locales are defined in /etc/locale.gen and can be genereated on the fly with locale-gen(8)[1].

Earlier versions

To install the needed locales, edit /etc/locales.build and write down the ones you need:
File: /etc/locales.build

Код: Выделить всё

de_DE/ISO-8859-1  # no euro char
de_DE@euro/ISO-8859-15  # with euro char
de_DE/UTF-8  # all chars ;)
The format is <locale>/<charmap>, where <locale> is a locale from the /usr/share/i18n/locales directory, and <charmap> is name of one of the files in usr/share/i18n/charmaps/

Each line is for a separate locale. You only use one locale at a time. If you only ever want to use a unicode locale, which includes the euro char (in fact, all chars), you only need the last line.)

Then you need to re-emerge your glibc with the useflag userlocales enabled. Check out chapter six of the Gentoo Handbook for more info.

If you need to install a locale not yet defined in /usr/share/i18n/locales, say sv_SE.UTF-8 if you want to have a swedish unicode layout, you need to type something similar to
Code:

Код: Выделить всё

localedef -i sv_SE -f UTF-8 sv_SE.UTF-8
in addition to writing sv_SE.UTF-8/UTF-8 in your /etc/locales.build, otherwise the system will not recognize your not yet defined keymap.

Take caution however, this should only be done if the keymap is not yet defined! (See Gentoo official UTF-8 documentation for more info)

Console setup

In ~root/.bashrc add
File: ~/.bashrc

Код: Выделить всё

if [[ $TERM = "linux" ]]; then
  unicode_start
fi
to set the console into unicode mode on root's login (use "unicode_start foo_font" to set your custom font).


But, since "unicode_start" requires root privileges, you can instead configure your Gentoo system to default to unicode consoles for all logins. For this to work, you must have a recent version of sys-apps/baselayout installed.

First, change the unicode setting in /etc/rc.conf
File: /etc/rc.conf

Код: Выделить всё

UNICODE="yes"

Then, to install a good font for UTF-8 consoles called terminus
Code: emerge terminus

Код: Выделить всё

emerge -av media-fonts/terminus-font

Also edit the following files, according to their comments:

Код: Выделить всё

/etc/conf.d/consolefont
/etc/conf.d/keymaps

One example for setting the console font is
File: /etc/conf.d/consolefont

Код: Выделить всё

CONSOLEFONT="ter-v16b"
#CONSOLETRANSLATION=""

Now, reboot the system, and the system INIT will automatically enable UTF-8 capability on all console logins. However, a particular console login won't actually display in UTF-8 until receiving a switch-to-unicode escape sequence.

The last step is to make the following change so that the switch-to-unicode escape sequence executes at each login
File: ~/.bash_profile

Код: Выделить всё

if test -t 1 -a -t 2 ; then
        echo -n -e '\033%G'
fi
This code instructs the console to switch to unicode if running from a console TTY (and not a terminal emulator or remote shell). In fact, this code block is directly from the internals of the "unicode_start" command.

Or, to make the switch to UTF-8 global for all users (could be problematic)
File: /etc/profile

Код: Выделить всё

if test -t 1 -a -t 2 ; then
        echo -n -e '\033%G'
fi

As a final, last-ditch alternative, you can use this init.d script to set all consoles into unicode mode on bootup:
File: /etc/init.d/unicode

Код: Выделить всё

#!/sbin/runscript
conf=/etc/env.d/02locale

# Using devfs?
if [ -e /dev/.devfsd ] || [ -e /dev/.udev -a -d /dev/vc ]; then
  device=/dev/vc/
else
  device=/dev/tty
fi

depend() {
        need localmount
        after keymaps
        before consolefont
}

checkconfig() {

  if [ -r ${conf} ]; then
          . ${conf}
          encoding=
          [ -n "${LC_ALL}" ]      && encoding=${LC_ALL#*.}   && return 0
          [ -n "${LC_MESSAGES}" ] && encoding=${LC_MESSAGES#*. } && return 0
          [ -n "${LANG}" ]        && encoding=${LANG#*.}   && return 0
  fi
  eend 1 "Locale is not configured, Please fix ${conf}"
  return 1
}

start() {
        ebegin "setting consoles to UTF-8"
        checkconfig
        if [[ "${encoding}" =~ "[uU][tT][fF]-?8" ]]; then
                dumpkeys | loadkeys --unicode
                for ((i=1; i <= "${RC_TTY_NUMBER}"; i++)); do
                        echo -ne "\033%G" > ${device}${i}
                done
                eend 0
        else
                eend 1 "UTF-8 is not required"
        fi
}
Code: to make script executable

Код: Выделить всё

chmod +x /etc/init.d/unicode 
and then
Code: add the script

Код: Выделить всё

rc-update add unicode default
Apps

Terminal emulators

xterm

xterm is running in unicode mode when started with:

Код: Выделить всё

xterm -u8
or
urxvt

urxvt from the rxvt-unicode package is always running in unicode mode. If you want it to use UTF-8, you have to set your LANG accordingly (eg LANG="en_US.utf8")

GNU Screen

GNU Screen must be invoked with the -U command line option.

If you are using it as a login shell you will have to write a wrapper that calls screen with the -U option and the options that are called when screen is used as a login shell:
Code: GNU Screen wrapper

Код: Выделить всё

#!/bin/sh
exec /usr/bin/screen -xRR -U
For people using it for irssi and so on, making an alias is enough.
File: ~/.bashrc

Код: Выделить всё

alias screen="screen -U"
However, if you are running screen from an SSH or RSH session, then editing the screen configuration should be enough.

Add the following to ~/.screenrc
File: ~/.screenrc

defutf8 on

Editors
Vim

Should work out of the box, since version 6.3 or so.

Nano

Nano versions prior to 1.3.6 can't handle utf8 properly. At the time of writing, this is only needed for the alpha and ppc-macos platforms.

Код: Выделить всё

echo "=app-editors/nano-1.3.6 ~alpha" >> /etc/portage/package.keywords
emerge -uDav nano
Editing

LaTeX

Merge unicode support for LaTeX
Code:

Код: Выделить всё

emerge dev-tex/latex-unicode
Mail

mutt

Mutt should work without a flaw on a unicode console. But if you want to use pretty-printing you need a few tricks as a2ps does not support utf-8. Your best bet may be using muttprint as it seems to work perfect both in unicode and single-byte environments and produces very elegant output. However it requires latex to be installed on your system.

Код: Выделить всё

emerge app-misc/muttprint
and then put this in your
File: ~/.muttrc

Код: Выделить всё

set print_command=muttprint
Otherwise you may emerge recode and a2ps:

Код: Выделить всё

emerge recode a2ps
and use this in
File: ~/.muttrc

Код: Выделить всё

set print_command="recode UTF-8..Latin-1 | a2ps -1 --portrait --borders=no -X latin1 --pretty-print=mail --strip 1 --highlight-level=heavy -P printername"
You may also use u2ps from the gnome-u2ps package (Debian gnome-u2ps package - don't know if it's also available in Gentoo). It has native Unicode support.

Shells

bash

Bash is unicode-aware since version 3 and when using readline version 5. Both are in portage.

Код: Выделить всё

emerge bash sys-libs/readline
revdep-rebuild --soname libreadline.so.4
rm /lib/libreadline.so.4*
be sure you know what you do when you perform the last step (see the info from the readline ebuild).

You will also need to have the package gentoolkit installed as it contains the revdep-rebuild tool.

zsh

Zsh handles UTF-8 perfectly since version 4.3.1. Older versions are not yet unicode aware. It still works as long as you dont use Backspace on unicode characters. (This deletes parts of the utf-8 character bytewise and confuses zle assumptions about the cursor position.)

mc

Mc must be compiled with the sys-libs/slang library for full unicode support.

Код: Выделить всё

 emerge euse
 euse -E slang
 emerge -avDN mc

X

X usually obeys the LC_* environment variables; however, X is picky about how you spell your locale settings. What works in the console may not work in X. You can find a list of all acceptable locale aliases in /usr/lib/X11/locale/locale.alias. As always, CaSe matters. You should make sure that the locale you choose corresponds to one of the glibc locales "locale -a".

If you're doing advanced troubleshooting you may also be interested in the locale.dir file, in the same directory. It maps locale names to files. Make sure it maps your locale correctly (it usually does).

So to sum it up, the chain goes like this, and all of its links must be intact: LC_* -> locale.alias -> locale.dir -> [X locale definition file]

fluxbox

BUG 1 Fluxbox doesn't fully support unicode yet. Some of its styles are selecting fonts that are not suitable for unicode. To fix this you will have to edit the Fluxbox's stylefile(s) in /usr/share/fluxbox/styles and add something like:
File: /usr/share/fluxbox/styles/$YourStyle

window.font: -*-*-*-*-*-*-*-*-*-*-*-*-*-u

to at least fix the window title bug.


BUG 2 Fluxbox takes very long to load on a utf-8 locale http://bugs.gentoo.org/show_bug.cgi?id=71747

patch for fluxbox-0.9.11 here: http://www.fluxmod.org.ua/

(patch has been merged with mainline as of 0.9.14)

OpenOffice.org

To enforce OpenOffice.org to use UTF-8 (you'll have problems when entering unicode characters) you have to set the LANGUAGE variable to an appropiate value:
File: /etc/env.d/02locales

Код: Выделить всё

LANG="de_DE.utf8"
...a lot of LC-Variables...
# For OpenOffice.org
LANGUAGE="en_GB:en"
Don't forget to run env-update && source /etc/profile after changing files in /etc/env.d/. Maybe you'll need to login again to apply the changes to your current environment.

Sound

Xmms

Easy method

In the Preferences -> Fonts window, just , change

Код: Выделить всё

-adobe-helvetica-bold-r-normal-*-*-100-*-*-p-*-iso8859-1
to

Код: Выделить всё

-adobe-helvetica-bold-r-normal-*-*-100-*-*-p-*-iso10646-1
This method seems only to work for the playlist, and for some reason not for the main window.

GTK 1.x method

XMMS use GTK 1.x and sometimes don't display utf-8. this is a little tweak. Just define a gtk1 font for the your user by creating (or editing) ~/.gtkrc:

Type "nano ~/.gtkrc" and put the following into the file.


File: ~/.gtkrc

Код: Выделить всё

style "user-font"
      fontset = "-misc-fixed-*-*-*-*-12-*-*-*-*-*-iso10646-1"
       
widget_class "*" style "user-font"
Converting an Old System

When preparing an old system to UTF-8, old encodings are likely to require some consideration. Especially, filenames and contents of plain text files might require re-encoding. Luckily, there are tools to do just this.

Converting Plain Text Files

The common tools to re-encode contents of plain text files are recode and iconv. Usually, recode is handier of these two as it supports in-place re-encoding.

Код: Выделить всё

 emerge app-text/recode
 recode iso8859-1..utf8 plain-text-file.txt
iconv comes with sys-libs/glibc, which you might have installed already.

Converting Filenames

convmv is a perl script utility to re-encode filenames, directory names, and entire subtrees. Emerge it with:

Код: Выделить всё

 emerge app-text/convmv
To test re-encoding a filename from ISO-8859-15 to UTF-8, try

Код: Выделить всё

 convmv -f iso-8859-15 -t utf8 file-name-with-ä
and if the produced command seems sane, add --notest to actually re-encode the name.

Links

* Gentoo official UTF-8 documentation
* Unicode HowTo from TLDP
* Detailed Overview of Using Unicode in Linux
Аватара пользователя
icedog
Site Admin
Сообщения: 229
Зарегистрирован: Пн авг 03, 2020 5:49 pm
Откуда: Краснодар
Контактная информация:

Re: Руководство по русской локализации Gentoo Linux

Сообщение icedog »

Using UTF-8 with Gentoo (Архив)
Thomas Martin Author
Alexander Simonov Contributor
Shyam Mani Editor

Updated March 19, 2006

1. Character Encodings

What is a Character Encoding?

Computers do not understand text themselves. Instead, every character is represented by a number. Traditionally, each set of numbers used to represent alphabets and characters (known as a coding system, encoding or character set) was limited in size due to limitations in computer hardware.

The History of Character Encodings

The most common (or at least the most widely accepted) character set is ASCII (American Standard Code for Information Interchange). It is widely held that ASCII is the most successful software standard ever. Modern ASCII was standardised in 1986 (ANSI X3.4, RFC 20, ISO/IEC 646:1991, ECMA-6) by the American National Standards Institute.

ASCII is strictly seven-bit, meaning that it uses bit patterns representable with seven binary digits, which provides a range of 0 to 127 in decimal. These include 32 non-visible control characters, most between 0 and 31, with the final control character, DEL or delete at 127. Characters 32 to 126 are visible characters: a space, punctuation marks, Latin letters and numbers.

The eighth bit in ASCII was originally used as a parity bit for error checking. If this is not desired, it is left as 0. This means that, with ASCII, each character is represented by a single byte.

Although ASCII was enough for communication in modern English, in other European languages that include accented characters, things were not so easy. The ISO 8859 standards were developed to meet these needs. They were backwards compatible with ASCII, but instead of leaving the eighth bit blank, they used it to allow another 127 characters in each encoding. ISO 8859's limitations soon came to light, and there are currently 15 variants of the ISO 8859 standard (8859-1 through to 8859-15). Outside of the ASCII-compatible byte range of these character sets, there is often conflict between the letters represented by each byte. To complicate interoperability between character encodings further, Windows-1252 is used in some versions of Microsoft Windows instead for Western European languages. This is a superset of ISO 8859-1, however it is different in several ways. These sets do all retain ASCII compatibility, however.

The necessary development of completely different single-byte encodings for non-Latin alphabets, such as EUC (Extended Unix Coding) which is used for Japanese and Korean (and to a lesser extent Chinese) created more confusion, while other operating systems still used different character sets for the same languages, for example, Shift-JIS and ISO-2022-JP. Users wishing to view cyrillic glyphs had to choose between KOI8-R for Russian and Bulgarian or KOI8-U for Ukrainian, as well as all the other cyrillic encodings such as the unsuccessful ISO 8859-5, and the common Windows-1251 set. All of these character sets broke most compatibility with ASCII (although KOI8 encodings place cyrillic characters in Latin order, so in case the eighth bit is stripped, text is still decipherable on an ASCII terminal through case-reversed transliteration.)

This has led to confusion, and also to an almost total inability for multilingual communication, especially across different alphabets. Enter Unicode.

What is Unicode?

Unicode throws away the traditional single-byte limit of character sets. It uses 17 "planes" of 65,536 code points to describe a maximum of 1,114,112 characters. As the first plane, aka. "Basic Multilingual Plane" or BMP, contains almost everything you will ever use, many have made the wrong assumption that Unicode was a 16-bit character set.

Unicode has been mapped in many different ways, but the two most common are UTF (Unicode Transformation Format) and UCS (Universal Character Set). A number after UTF indicates the number of bits in one unit, while the number after UCS indicates the number of bytes. UTF-8 has become the most widespread means for the interchange of Unicode text as a result of its eight-bit clean nature, and it is the subject of this document.

UTF-8

UTF-8 is a variable-length character encoding, which in this instance means that it uses 1 to 4 bytes per symbol. So, the first UTF-8 byte is used for encoding ASCII, giving the character set full backwards compatibility with ASCII. UTF-8 means that ASCII and Latin characters are interchangeable with little increase in the size of the data, because only the first bit is used. Users of Eastern alphabets such as Japanese, who have been assigned a higher byte range are unhappy, as this results in as much as a 50% redundancy in their data.

What UTF-8 Can Do for You

UTF-8 allows you to work in a standards-compliant and internationally accepted multilingual environment, with a comparatively low data redundancy. UTF-8 is the preferred way for transmitting non-ASCII characters over the Internet, through Email, IRC or almost any other medium. Despite this, many people regard UTF-8 in online communication as abusive. It is always best to be aware of the attitude towards UTF-8 in a specific channel, mailing list or Usenet group before using non-ASCII UTF-8.

2. Setting up UTF-8 with Gentoo Linux

Finding or Creating UTF-8 Locales

Now that you understand the principles behind Unicode, you're ready to start using UTF-8 with your system.

The preliminary requirement for UTF-8 is to have a version of glibc installed that has national language support. The recommend means to do this is the /etc/locales.build file in combination with the userlocales USE flag. It is beyond the scope of this document to explain the usage of this file though, luckily, the usage of this file is well documented in the comments within it. It is also explained in the Gentoo Localisation Guide.

Next, we'll need to decide whether a UTF-8 locale is already available for our language, or whether we need to create one.

Code Listing 2.1: Checking for an existing UTF-8 locale

(Replace "en_GB" with your desired locale setting)

Код: Выделить всё

# locale -a | grep 'en_GB'
en_GB
en_GB.UTF-8
From the output of this command line, we need to take the result with a suffix similar to .UTF-8. If there is no result with a suffix similar to .UTF-8, we need to create a UTF-8 compatible locale.

Note: Only execute the following code listing if you do not have a UTF-8 locale available for your language.

Code Listing 2.2: Creating a UTF-8 locale

(Replace "en_GB" with your desired locale setting)

Код: Выделить всё

# localedef -i en_GB -f UTF-8 en_GB.UTF-8
Another way to include a UTF-8 locale is to add it to the /etc/locales.build file and rebuild glibc with the userlocales USE flag set.

Code Listing 2.3: Line in /etc/locales.build

Код: Выделить всё

en_GB.UTF-8/UTF-8
Setting the Locale

There is one environment variable that needs to be set in order to use our new UTF-8 locales: LC_ALL (this variable overrides the LANG setting as well). There are also many different ways to set it; some people prefer to only have a UTF-8 environment for a specific user, in which case they set them in their ~/.profile (if you use /bin/sh), ~/.bash_profile or ~/.bashrc (if you use /bin/bash).

Others prefer to set the locale globally. One specific circumstance where the author particularly recommends doing this is when /etc/init.d/xdm is in use, because this init script starts the display manager and desktop before any of the aforementioned shell startup files are sourced, and so before any of the variables are in the environment.

Setting the locale globally should be done using /etc/env.d/02locale. The file should look something like the following:

Code Listing 2.4: Demonstration /etc/env.d/02locale

(As always, change "en_GB.UTF-8" to your locale)

Код: Выделить всё

LC_ALL="en_GB.UTF-8"
Next, the environment must be updated with the change.

Code Listing 2.5: Updating the environment

Код: Выделить всё

# env-update
>>> Regenerating /etc/ld.so.cache...
 * Caching service dependencies ...
# source /etc/profile
Now, run locale with no arguments to see if we have the correct variables in our environment:

Code Listing 2.6: Checking if our new locale is in the environment

Код: Выделить всё

# locale
LANG=
LC_CTYPE="en_GB.UTF-8"
LC_NUMERIC="en_GB.UTF-8"
LC_TIME="en_GB.UTF-8"
LC_COLLATE="en_GB.UTF-8"
LC_MONETARY="en_GB.UTF-8"
LC_MESSAGES="en_GB.UTF-8"
LC_PAPER="en_GB.UTF-8"
LC_NAME="en_GB.UTF-8"
LC_ADDRESS="en_GB.UTF-8"
LC_TELEPHONE="en_GB.UTF-8"
LC_MEASUREMENT="en_GB.UTF-8"
LC_IDENTIFICATION="en_GB.UTF-8"
LC_ALL=en_GB.UTF-8
That's everything. You are now using UTF-8 locales, and the next hurdle is the configuration of the applications you use from day to day.

3. Application Support

When Unicode first started gaining momentum in the software world, multibyte character sets were not well suited to languages like C, in which many of the day-to-day programs people use are written. Even today, some programs are not able to handle UTF-8 properly. Fortunately, most are!

Filenames, NTFS, and FAT

There are several NLS options in the Linux kernel configuration menu, but it is important to not become confused! For the most part, the only thing you need to do is to build UTF-8 NLS support into your kernel, and change the default NLS option to utf8.

Code Listing 3.1: Kernel configuration steps for UTF-8 NLS

Код: Выделить всё

File Systems -->
  Native Language Support -->
    (utf8) Default NLS Option
    <*> NLS UTF8
    (Also <*> other character sets that are in use in
    your FAT filesystems or Joilet CD-ROMs.)
If you plan on mounting NTFS partitions, you may need to specify an nls= option with mount. If you plan on mounting FAT partitions, you may need to specify a codepage= option with mount. Optionally, you can also set a default codepage for FAT in the kernel configuration. Note that the codepage option with mount will override the kernel settings.

Code Listing 3.2: FAT settings in kernel configuration

Код: Выделить всё

File Systems -->
  DOS/FAT/NT Filesystems  -->
    (437) Default codepage for fat
You should avoid setting Default iocharset for fat to UTF-8, as it is not recommended. Instead, you may want to pass the option utf8=true when mounting your FAT partitions. For further information, see man mount and the kernel documentation at /usr/src/linux/Documentation/filesystems/vfat.txt.

For changing the encoding of filenames, app-text/convmv can be used.

Code Listing 3.3: Example usage of convmv

Код: Выделить всё

# emerge --ask app-text/convmv
(Command format)
# convmv -f <current-encoding> -t utf-8 <filename>
(Substitute iso-8859-1 with the charset you are converting
from)
# convmv -f iso-8859-1 -t utf-8 filename
For changing the contents of files, use the iconv utility, bundled with glibc:

Code Listing 3.4: Example usage of iconv

(substitute iso-8859-1 with the charset you are converting from)
(Check the output is sane)

Код: Выделить всё

# iconv -f iso-8859-1 -t utf-8 filename 
(Convert a file, you must create another file)

Код: Выделить всё

# iconv -f iso-8859-1 -t utf-8 filename > newfile
app-text/recode can also be used for this purpose.

The System Console

Important: You need >=sys-apps/baselayout-1.11.9 for Unicode on the console.

To enable UTF-8 on the console, you should edit /etc/rc.conf and set UNICODE="yes", and also read the comments in that file -- it is important to have a font that has a good range of characters if you plan on making the most of Unicode.

The KEYMAP variable, set in /etc/conf.d/keymaps, should have a Unicode keymap specified.

Code Listing 3.5: Example /etc/conf.d/keymaps snippet

Код: Выделить всё

(Change "uk" to your local layout)
KEYMAP="uk"
Ncurses and Slang

Note: Ignore any mention of Slang in this section if you do not have it installed or do not use it.

It is wise to add unicode to your global USE flags in /etc/make.conf, and then to remerge sys-libs/ncurses and sys-libs/slang if appropriate. Portage will do this automatically when you update your system:

Code Listing 3.6: Updating your system

Код: Выделить всё

# emerge --update --deep --newuse world
We also need to rebuild packages that link to these, now the USE changes have been applied. The tool we use (revdep-rebuild) is part of the gentoolkit package.

Code Listing 3.7: Rebuilding of programs that link to ncurses or slang

Код: Выделить всё

# revdep-rebuild --soname libncurses.so.5
# revdep-rebuild --soname libslang.so.1
KDE, GNOME and Xfce

All of the major desktop environments have full Unicode support, and will require no further setup than what has already been covered in this guide. This is because the underlying graphical toolkits (Qt or GTK+2) are UTF-8 aware. Subsequently, all applications running on top of these toolkits should be UTF-8-aware out of the box.

The exceptions to this rule come in Xlib and GTK+1. GTK+1 requires a iso-10646-1 FontSpec in the ~/.gtkrc, for example -misc-fixed-*-*-*-*-*-*-*-*-*-*-iso10646-1. Also, applications using Xlib or Xaw will need to be given a similar FontSpec, otherwise they will not work.

Note: If you have a version of the gnome1 control center around, use that instead. Pick any iso10646-1 font from there.

Code Listing 3.8: Example ~/.gtkrc (for GTK+1) that defines a Unicode compatible font

Код: Выделить всё

style "user-font"
{
    fontset="-misc-fixed-*-*-*-*-*-*-*-*-*-*-iso10646-1"
}
widget_class "*" style "user-font"
If an application has support for both a Qt and GTK+2 GUI, the GTK+2 GUI will generally give better results with Unicode.

X11 and Fonts

Important: x11-base/xorg-x11 has far better support for Unicode than XFree86 and is highly recommended.

TrueType fonts have support for Unicode, and most of the fonts that ship with Xorg have impressive character support, although, obviously, not every single glyph available in Unicode has been created for that font. To build fonts (including the Bitstream Vera set) with support for East Asian letters with X, make sure you have the cjk USE flag set. Many other applications utilise this flag, so it may be worthwhile to add it as a permanent USE flag.

Also, several font packages in Portage are Unicode aware.

Code Listing 3.9: Optional: Install some more Unicode-aware fonts

Код: Выделить всё

# emerge terminus-font intlfonts freefonts cronyx-fonts corefonts
Window Managers and Terminal Emulators

Window managers not built on GTK or Qt generally have very good Unicode support, as they often use the Xft library for handling fonts. If your window manager does not use Xft for fonts, you can still use the FontSpec mentioned in the previous section as a Unicode font.

Terminal emulators that use Xft and support Unicode are harder to come by. Aside from Konsole and gnome-terminal, the best options in Portage are x11-terms/rxvt-unicode, xfce-extra/terminal, gnustep-apps/terminal, x11-terms/mlterm, or plain x11-terms/xterm when built with the unicode USE flag and invoked as uxterm. app-misc/screen supports UTF-8 too, when invoked as screen -U or the following is put into the ~/.screenrc:

Code Listing 3.10: ~/.screenrc for UTF-8

Код: Выделить всё

defutf8 on
Vim, Emacs, Xemacs and Nano

Vim provides full UTF-8 support, and also has builtin detection of UTF-8 files. For further information in Vim, use :help mbyte.txt.

Emacs 22.x and higher has full UTF-8 support as well. Xemacs 22.x does not support combining characters yet.

Lower versions of Emacs and/or Xemacs might require you to install app-emacs/mule-ucs and/or app-xemacs/mule-ucs and add the following code to your ~/.emacs to have support for CJK languages in UTF-8:

Code Listing 3.11: Emacs CJK UTF-8 support

Код: Выделить всё

(require 'un-define)
(require 'jisx0213)
(set-language-environment "Japanese")
(set-default-coding-systems 'utf-8)
(set-terminal-coding-system 'utf-8)
Nano has provided full UTF-8 support since version 1.3.6.

Shells

Currently, bash provides full Unicode support through the GNU readline library. Z Shell users are in a somewhat worse position -- no parts of the shell have Unicode support, although there is a concerted effort to add multibyte character set support underway at the moment.

The C shell, tcsh and ksh do not provide UTF-8 support at all.

Irssi

Irssi has complete UTF-8 support, although it does require a user to set an option.

Code Listing 3.12: Enabling UTF-8 in Irssi

Код: Выделить всё

/set term_charset UTF-8
For channels where non-ASCII characters are often exchanged in non-UTF-8 charsets, the /recode command may be used to convert the characters. Type /help recode for more information.

Mutt

The Mutt mail user agent has very good Unicode support. To use UTF-8 with Mutt, you don't need to put anything in your configuration files. Mutt will work under unicode enviroment without modification if all your configuration files (signature included) are UTF-8 encoded.

Note: You may still see '?' in mail you read with Mutt. This is a result of people using a mail client which does not indicate the used charset. You can't do much about this than to ask them to configure their client correctly.

Further information is available from the Mutt Wiki.

Less

We all use a lot of more or less along with the | to be able to correctly see the output of a command, like for example dmesg | less. While more only needs the shell to be UTF-8 aware, less needs an environment variable set, LESSCHARSET to ensure that unicode characters are rendered correctly. This can be set in /etc/profile or ~/.bash_profile. Fire up the editor of your choice and the add the following line to one of the files mentioned above.

Code Listing 3.13: Setting up the Environment variable for less

Код: Выделить всё

LESSCHARSET=utf-8
Man

Man pages are an integral part of any Linux machine. To ensure that any unicode in your man pages render correctly, edit /etc/man.conf and replace a line as shown below.

Code Listing 3.14: man.conf changes for Unicode support

(This is the old line)

Код: Выделить всё

NROFF           /usr/bin/nroff -Tascii -c -mandoc
(Replace the one above with this)
NROFF           /usr/bin/nroff -mandoc -c
elinks and links

These are commonly used text-based browsers, and we shall see how we can enable UTF-8 support on them. On elinks and links, there are two ways to go about this, one using the Setup option from within the browser or editing the config file. To set the option through the browser, open a site with elinks or links and then Alt+S to enter the Setup Menu then select Terminal options, or press T. Scroll down and select the last option UTF-8 I/O by pressing Enter. Then Save and exit the menu. On links you may have to do a repeat Alt+S and then press S to save. The config file option, is shown below.

Code Listing 3.15: Enabling UTF-8 for elinks/links

(For elinks, edit /etc/elinks/elinks.conf or ~/.elinks/elinks.conf and
add the following line)

Код: Выделить всё

set terminal.linux.utf_8_io = 1
(For links, edit ~/.links/links.cfg and add the following
line)

Код: Выделить всё

terminal "xterm" 0 1 0 us-ascii utf-8
Testing it all out

There are numerous UTF-8 test websites around. net-www/w3m, net-www/links, net-www/elinks, net-www/lynx and all Mozilla based browsers (including Firefox) support UTF-8. Konqueror and Opera have full UTF-8 support too.

When using one of the text-only web browsers, make absolutely sure you are using a Unicode-aware terminal.

If you see certain characters displayed as boxes with letters or numbers inside, this means that your font does not have a character for the symbol or glyph that the UTF-8 wants. Instead, it displays a box with the hex code of the UTF-8 symbol.

* A W3C UTF-8 Test Page
* A UTF-8 test page provided by the University of Frankfurt

Input Methods

Dead keys may be used to input characters in X that are not included on your keyboard. These work by pressing your right Alt key (or in some countries, AltGr) and an optional key from the non-alphabetical section of the keyboard to the left of the return key at once, releasing them, and then pressing a letter. The dead key should modify it. Input can be further modified by using the Shift key at the same time as pressing the AltGr and modifier.

To enable dead keys in X, you need a layout that supports it. Most European layouts already have dead keys with the default variant. However, this is not true of North American layouts. Although there is a degree of inconsistency between layouts, the easiest solution seems to be to use a layout in the form "en_US" rather than "us", for example. The layout is set in /etc/X11/xorg.conf like so:

Code Listing 3.16: /etc/X11/xorg.conf snippet

Код: Выделить всё

Section "InputDevice"
    Identifier "Keyboard0"
    Driver     "kbd"
    Option     "XkbLayout" "en_US" # Rather than just "us"
    (Other Xkb options here)
EndSection
Note: The preceding change only needs to be applied if you are using a North American layout, or another layout where dead keys do not seem to be working. European users should have working dead keys as is.

This change will come into effect when your X server is restarted. To apply the change now, use the setxkbmap tool, for example, setxkbmap en_US.

It is probably easiest to describe dead keys with examples. Although the results are locale dependent, the concepts should remain the same regardless of locale. The examples contain UTF-8, so to view them you need to either tell your browser to view the page as UTF-8, or have a UTF-8 locale already configured.

When I press AltGr and [ at once, release them, and then press a, 'ä' is produced. When I press AltGr and [ at once, and then press e, 'ë' is produced. When I press AltGr and ; at once, 'á' is produced, and when I press AltGr and ; at once, release them, and then press e, 'é' is produced.

By pressing AltGr, Shift and [ at once, releasing them, and then pressing a, a Scandinavian 'å' is produced. Similarly, when I press AltGr, Shift and [ at once, release only the [, and then press it again, '˚' is produced. Although it looks like one, this (U+02DA) is not the same as a degree symbol (U+00B0). This works for other accents produced by dead keys — AltGr and [, releasing only the [, then pressing it again makes '¨'.

AltGr can be used with alphabetical keys alone. For example, AltGr and m, a Greek lower-case letter mu is produced: 'µ'. AltGr and s produce a scharfes s or esszet: 'ß'. As many European users would expect (because it is marked on their keyboard), AltGr and 4 (or E depending on the keyboard layout) produces a Euro sign, '€'.
Аватара пользователя
icedog
Site Admin
Сообщения: 229
Зарегистрирован: Пн авг 03, 2020 5:49 pm
Откуда: Краснодар
Контактная информация:

Re: Руководство по русской локализации Gentoo Linux

Сообщение icedog »

HOWTO ru RU.utf8 Gentoo way (Дальше не буду копировать архив)

Ставим шрифты

Код: Выделить всё

emerge terminus-font intlfonts freefonts cronyx-fonts corefonts artwiz-fonts
Примечание: В принципе достаточно terminus-font, а остальное если только для полного счастья

Последние полгода (это очень давно было написано) glibc собирается с ru_RU.UTF-8 уже "из коробки". Так что сначала проверьте, может у вас уже всё есть(необходимо наличие ru_RU.utf8):

Код: Выделить всё

Code: locale -a | grep ru
ru_RU
ru_RU.cp1251
ru_RU.koi8r
ru_RU.utf8
В случае, если у вас не собрана локаль, то можно ее создать вручную или пересобрать glibc.

1. Для создания локaли командой

Код: Выделить всё

localedef
вам потребуются права root'а.

Код: Выделить всё

localedef --no-archive -c -i ru_RU -f UTF-8 ru_RU.utf8
Обратите внимание на опцию --no-archive она указывает на то, что локаль не надо упаковывать в архив. Если вы забудете указать эту опцию, то после обновления библиотеки glibc вам придется повторить этот шаг снова.

По обсуждениям в форуме этой статьи можно заметить, что есть некоторые проблемы. Если команда locale выдаёт ошибки следующего вида:

Код: Выделить всё

Code: locale
locale: Cannot set LC_CTYPE to default locale: No such file or directory
locale: Cannot set LC_MESSAGES to default locale: No such file or directory
locale: Cannot set LC_ALL to default locale: No such file or directory
Тогда лучше определить локаль следующей командой

Код: Выделить всё

localedef --no-archive -c -i ru_RU -f UTF-8 ru
2. В последних версиях glibc у вас есть возможность определить список локалей, которые вы хотите использовать. Вкратце:

Код: Выделить всё

File: /etc/locales.build
# кодировка для ru_RU по умолчанию
ru_RU/KOI8-R
# при желании можно будет вернутся к KOI8-R
ru_RU.KOI8-R/KOI8-R
# То к чему стремимся
ru_RU.UTF-8/UTF-8
# Не помешает также
ru_RU.CP1251/CP1251
Пересобираем glibc с флагом userlocales:

Код: Выделить всё

USE="userlocales" emerge glibc
Настройка

Переменные окружения
Надо в файле /etc/env.d/02locale прописать две строки:

Код: Выделить всё

File: /etc/env.d/02locale
LC_ALL=""
LANG="ru_RU.UTF-8"
Однако предпочтительней это делать в файлах пользователя, например ~/.bash_profile.

Предупреждение: Не устанавливайте переменную LESSCHARSET равной UTF-8! Это приведет к неработоспособности как самой программы less(1), так и связанных с ней - таких как man(1).
Чтобы это изменение вступило в силу немедленно, выполните:

Код: Выделить всё

env-update && source /etc/profile
Файлы настройки системы

Нужно также изменить несколько файлов запуска системы. Все эти файлы входят в пакет baselayout, последние версии которого содержат ряд изменений упрощающих настройку и наиболее удобны для использования. Лучше всего обновить пакет до версии 1.11.9 или выше, но если у вас нет возможности этого сделать, то ниже приведены варианты и для старых версий.

В процессе настройки файлов вам будет необходимо выбрать вариант раскладки клавиатуры. Для каждой раскладки клавиатуры определена кодировка и ее необходимо указать с помощью опции DUMPKEYS_CHARSET, тогда система будет автоматически конвертировать кодировку раскладки в кодировку вашей локали(в данном случае UTF-8).

baselayout >= 1.11.9

В случае baselayout версии 1.11.9 и выше

File: /etc/rc.conf

Код: Выделить всё

UNICODE="yes"
File: /etc/conf.d/consolefont

Код: Выделить всё

CONSOLEFONT="ter-k14n"
File: /etc/conf.d/keymaps

Код: Выделить всё

KEYMAP="-u ru4"
SET_WINDOWKEYS="yes" # Опционально
DUMPKEYS_CHARSET="koi8-r"
baselayout >= 1.11.7

В случае baselayout версии 1.11.7 и выше:

File: /etc/rc.conf

Код: Выделить всё

CONSOLEFONT="ter-k14n"
UNICODE="yes"
File: /etc/conf.d/keymaps

Код: Выделить всё

KEYMAP="-u ru4"
SET_WINDOWKEYS="yes" # Опционально
DUMPKEYS_CHARSET="koi8-r"
baselayout >= 1.11.4

Если у вас baselayout версии от 1.11.4 до 1.11.7, то вам нужно сделать следующее: В файле /etc/rc.conf надо прописать

File: /etc/rc.conf

Код: Выделить всё

KEYMAP="-u ru4"
CONSOLEFONT="ter-k14n"
UNICODE="yes"
И еще надо подредактировать /etc/init.d/keymaps строку

Код: Выделить всё

dumpkeys | loadkeys --unicode
заменить на

Код: Выделить всё

dumpkeys -c koi8-r | loadkeys --unicode
В 2005.1 rc1 это делать не нужно

Проверка локали

Заключительным аккордом дожен стать перезапуск сервисов keymaps и consolefont.

Код: Выделить всё

 /etc/init.d/keymaps restart

Код: Выделить всё

/etc/init.d/consolefont restart
Лучше так:

Код: Выделить всё

 /etc/init.d/keymaps restart&&/etc/init.d/consolefont restart
Теперь у вас должна быть локаль ru_RU.UTF-8

Код: Выделить всё

Code: locale
LANG=ru_RU.UTF-8
LC_CTYPE="ru_RU.UTF-8"
LC_NUMERIC="ru_RU.UTF-8"
LC_TIME="ru_RU.UTF-8"
LC_COLLATE="ru_RU.UTF-8"
LC_MONETARY="ru_RU.UTF-8"
LC_MESSAGES="ru_RU.UTF-8"
LC_PAPER="ru_RU.UTF-8"
LC_NAME="ru_RU.UTF-8"
LC_ADDRESS="ru_RU.UTF-8"
LC_TELEPHONE="ru_RU.UTF-8"
LC_MEASUREMENT="ru_RU.UTF-8"
LC_IDENTIFICATION="ru_RU.UTF-8"
LC_ALL=
Последняя редакция этой статьи вроде 2005 год
Ответить