Как подключить русский язык в latex

от admin

LaTeX/Использование разных языков

Для написания в LaTeX документов на языках, отличных от английского, необходимо указать:

  1. как расставлять переносы в словах выбранного языка;
  2. как использовать правила типографского набора для выбранного языка (например, во французском языке перед каждым символом двоеточия (:) ставится обязательный пробел);
  3. как вводить специальные символы, особенно для языков с системой ввода (арабский, китайский, японский, корейский).

Удобно, когда есть возможность вставлять специальные символы выбранного языка непосредственно с клавиатуры, а не использовать громоздкий код (например, вместо \" просто ввести ä). Для этого нужно настроить внутреннюю кодировку символов, подробности см. в Специальные символы.

Для некоторых языков требуются специальные шрифты с соответствующим набором кодирования, см. Кодировка шрифта.

Некоторые из методов, описанных в этой главе, пригодятся при наборе имён неанглоязычных авторов для библиографического списка.

В этом разделе собраны советы о том, как в LaTeX написать документ на любом другом языке, кроме английского. Если у Вас есть подобный опыт использования языка, который не указан в списке, пожалуйста добавьте несколько замечаний.

Необходимые условия [ править ]

Для многих отличных от английского языков часто необходимо использовать специальные символы. Для этого нужно установить внутреннюю кодировку и кодировку шрифта.

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

Для получения дополнительной информации см. Кодировка шрифта и Специальные символы.

Пакет babel [ править ]

Пакет babel, созданный Йоганнесом Браамсом (Johannes Braams), отвечает за

  • правила расстановки переносов;
  • новые команды, упрощающие ввод специальных символов.

Чтобы подключить пакет babel, добавьте в преамбулу документа:

В качестве аргумента укажите нужный Вам язык.

По возможности эту строчку необходимо добавить сразу же после команды \documentclass. В этом случае для всех остальных загружаемых пакетов будет использоваться выбранный язык. Список языков, подключаемых в установленной у Вас системе LaTeX, отображается при каждой компиляции документа. Если установленный Вами формат LaTeX не поддерживает расстановку переносов выбранного языка, то пакет babel будет продолжать свою работу, отключив расстановку переносов. Это отрицательно скажется только на внешнем виде документа.

Можно выбрать несколько языков набора текста:

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

Для вставки небольшого кусочка текста на другом языка также можно использовать команду

Если нужно вставить большой кусок текста на другом языке, используйте окружение:

Окружение otherlanguage* набирает основной текст согласно правилам другого языка, но при этом использует основной язык для названий вспомогательных конструкций (подписи к рисункам и т.д.). Окружение hyphenrules переключается только правила расстановки переносов. Чтобы запретить расстановку переносов, в качестве аргумента команды укажите nohyphenation.

Кириллица [ править ]

Пакет babel, начиная с версии 3.7, поддерживает кодировку T2* и вёрстку текстов на русском, болгарском и украинском языках с использованием кириллических символов. Поддержка кириллицы основана на стандартных механизмах LaTeX с дополнительным использованием пакетов fontenc и inputenc. Пакеты AMS-LaTeX необходимо подключить перед пакетами fontenc и babel. Чтобы использовать кириллицу в математических формулах, перед пакетом fontenc подключите пакет mathtext:

Вообще говоря, пакет babel автоматически выберет кодировку шрифта по умолчанию: для русского, болгарского и украинского языков это будет T2A. Однако для многоязыковых документов, в которых используются языки, основанные на кириллице и латинице, имеет смысл явно указать латинскую кодировку шрифтов. Пакет babel сам переключит нужную кодировку шрифта при смене языка в тексте документа.

На современных операционных системах в качестве внутренней кодировки кириллических текстов лучше всего использовать Unicode (utf8 or utf8x), а не KOI8-RU (koi8-ru).

Дополнительно к подключению правил расстановки переносов, переводу автоматически создаваемых текстовых строк и активации некоторых специфичных для языка типографских правил (например, \frenchspacing – обязательный пробел перед двоеточием во французском языке), пакет babel представляет несколько команд для вёрстки текста согласно стандартам русского, болгарского и украинского языков.

Для указанных языков обеспечивается специфическая пунктуация: кириллическое тире для текста (оно слегка уже латинского тире и окружено крошечными пробелами), тире для обозначения прямой речи, кавычки, команды для более простой расстановки переносов:

Для подключаемых с помощью пакета babel русского и украинского языков определены команды \Asbuk и \asbuk, которые, аналогично командам \Alph and \alph, переключают регистр букв русского или украинского алфавита (в зависимости от текущего языка документа). Для болгарского языка команды \enumBul, \enumLat, \enumEng переключают регистр для болгарского, латинского, английского языка, соответственно.

Introduction

This article explores typesetting Russian text: enabling correct use of Cyrillic characters, such аs ц, ч, ш, щ, ъ etc., and providing support for language-specific features such as hyphenation. If you are looking for instructions on how to use more than one language in a single document, for instance English and Russian, see the International language support article.

Russian example using pdfLaTeX

We’ll start with the following pdfLaTeX example which you can open in Overleaf using the link below the code. Because Russian uses the Cyrillic script pdfLaTeX needs to ensure it not only handles the input (encoding) of Cyrillic text but also ensure the correct (output) encoding is applied to any fonts used to typeset the document. These encoding issues are discussed below.

This example produces the following output:

Background topics: characters and encodings

The following sections provide background material on topics related to typesetting different languages using LaTeX (mostly related to pdfLaTeX).

Text files: integers and characters

Any text file, such as a LaTeX input .tex file, is nothing more than a stream of numeric (integer) values which are being used as a mechanism to represent characters of text; consequently, processing a text file involves scanning (reading/processing) a series of integer values. However, an important question arises: which set of characters is actually represented by the integer values contained in a particular text file? In other words, how have those integer values been encoded: what is the correct (intended) "mapping" (encoding) from integers in the text file to the corresponding characters they are supposed to represent?

Text files can be generated within innumerable computing environments: across different countries/continents, using a multitude of different devices, operating systems and editing tools. Originators of text files could, potentially, use or apply different text encodings according to local requirements, such as language, when generating and storing the sequence of integer values chosen to represent the individual characters contained in a text file. This may work well if the generated text files stayed within compatible technical ecosystems, which use the same encoding, but what would happen when those files are transferred to completely different environments—because many text files do not contain any information which indicates the encoding used to generate them.

Clearly, the producer (originator) and consumer (user) of textual data must, somehow, agree on the encoding (mapping) being used, otherwise encoding errors are likely to arise due to mismatches between the integer data in the file and the set of characters it is assumed to represent. In addition to correctly mapping text file integer values to characters, any subsequent visual display of those characters requires some form of font that is capable of providing the data (shapes, or even bitmaps) to output a visual representation of the desired characters.

Input encoding: inputenc , UTF-8 and a change to LaTeX in 2018

Historically, a variety of 8-bit encodings were used to generate/process text files, including LaTeX inputs. To cut short a very long story, the developers of LaTeX created the inputenc package to address encoding issues—allowing text files, created using various encodings, to be transferred between disparate LaTeX installations.

However, over time, users/software developers moved away from multiple 8-bit encodings to using Unicode and its UTF-8 encoding scheme, which became the de facto option for encoding text files. Prior to 2018, to process UTF-8 encoded files LaTeX document preambles included the line

Readers might observe that the example above does not include the line \usepackage[utf8] in the document preamble: why is that? This is due to an important change to LaTeX introduced in 2018: a switch to UTF-8 as the default input encoding. Documents typeset with pdfLaTeX, and using UTF-8 encoded text, including those created and typeset on Overleaf, no longer need to include \usepackage[utf8] but is does no harm to do so. For further information see the April 2018 issue of LaTeX News and the Overleaf blog post TeX Live upgrade—September 2019. All text files created on Overleaf are encoded using UTF-8.

Читать:
Как остановить поиск решений в excel

Output encoding: the fontenc package (for use with pdfLaTeX)

To correctly typeset characters contained within input files, those characters need to be mapped to the appropriate output shapes (glyphs) contained in fonts used to typeset the document. This “output encoding” is handled by another package called fontenc .

To use fontenc include the following line in your document preamble, using an encoding, such as the T2A encoding, which supports the Cyrillic script:

The following chart lists the T2A font encoding for Cyrillic text. It is reproduced from page 23 of the document LaTeX font encodings which is available on CTAN.

Language-specific packages and commands

To extended the default L a T e X capabilities, for proper hyphenation and translating the names of the document elements, import the babel package and use the russian language option:

As you may see in the example in the introduction, instead of "Abstract" and "Contents" the Russian words "Аннотация" and "Содержание" are used. Cyrillic characters can also be used in mathematical mode.

If you need to include more than one language, for instance, Russian and English, see the International language support article to learn how to achieve this. A great deal of useful background information can be found in the document Russian language module for Babel.

Hyphenation

To achieve linebreaks, some words have to be hyphenated: broken up into syllables separated by a - (hyphen), allowing the word to continue on the next line. For example, математика could become мате-мати-ка. The babel package usually does a good job of hyphenation but, occasionally, you may need to define hyphenation points manually, which you can do using these commands in the preamble:

\usepackage imports the hyphenat package and the second line is a list of space-separated words with defined hyphenation points. If you want to prevent automatic hyphenation of a particular word , use the command <\nobreak word> within your document.

A final example

This final example configures LaTeX so that the Russian text can be typeset using pdfLaTeX, XeLaTeX and LuaLuaTeX—to switch compilers on Overleaf, see the article Changing compiler.

This example uses the \iftutex command from the iftex package to detect whether a Unicode-aware engine (LuaTeX or XeTeX) is being used to compile the LaTeX code (document). If so, Google's OpenType Noto fonts are configured via the fontspec package and used to typeset the document. If a non-Unicode-aware engine, such as pdfTeX, is detected then the LaTeX code (document) is typeset using old 8-bit font technologies (based on Adobe Type 1).

The following code opens on Overleaf and defaults to compiling with XeLaTeX. To use a different compiler, see the article Changing compiler.

Cyrillic in (La)TeX

What are different ways to use Cyrillic in (La)TeX? What are their pros and cons?

7 Answers 7

inputenc + babel

Usage

Standard — works with any LaTeX installation. One can use any encoding in .tex files. Works fine with hyperref .

Cyrillic letters become active symbols — so one can neither define commands with Cyrillic names nor use them in arguments of \label , \cite etc. Cyrillic letters in .aux and .toc files become unreadable.

Note
If you get this error: Unknown option 'russian'. Either you misspelled it or the language definition file francais.ldf was not found try installing the texlive-lang-cyrillic package. (source)

For multilingual texts with pdflatex (as opposed to using the xelatex or lualatex engines), the best option is to use the UTF-8 encoding for the input and babel :

enter image description here

There are a number of fonts available in the T2A encoding for pdflatex :

enter image description here

For a wider choice, XeLaTeX or LuaLaTeX are best.

XeLaTeX

Usage

Compile with xelatex .

Works out of the box in fresh TeX distributions. Cyrillic letters can be used freely in control sequence names, labels, etc.

One needs a pretty modern TeX distribution. (What else?)

Mixing Cyrillic and Latin letters

The basic idea is to use babel and inputenc (like inputenc+babel). Your document looks like:

Especially important is OT2 -encoding and russian as option to babel . The command \foreignlanguage allows you to switch between English and Russian.

  • You don't need a Cyrillic keyboard.
  • Nearly every LaTeX system has OT2 .
  • babel also offers specific names e.g. for the table of contents (Содержание), table of ..
  • Hyphenation does not work perfect.
  • Using OT2 encoding is like a poor man's alternative to T2A

Some time ago I wrote a blog post in German: Kyrillischen Text mit LaTeX setzen

Using UTF-8

If you're using UTF-8, you have a Russian keyboard and you want to type only Russian texts, the best would be:

This way you don't have to change your behaviour. Typing LaTeX texts is as easy as typing other texts. Usually you also have correct hyphenation patterns, so you can use the full feature set of LaTeX. 🙂

Cherepanov's russlh

Usage

Cyrillic letters are \catcode 'd to 11 ("letter"); thus, they can be used freely in control sequence names, labels, etc. In text files written by LaTeX (.toc, .aux, .idx, etc.) Russian letters are recoded back to their initial form, which makes these files readable and simplifies the processing of .idx files.

One has to (download and) use a non-standard package. Doesn't work with hyperref (at least not with the current version).

LuaLaTeX

Another modern option for Cyrillics is LuaLaTeX (with babel or polyglossia , though polyglossia still has an annoying bug and forgets to switch font family/shape sometimes).

Usage

LuaLaTeX can use any TTF or OTF font without any additional work like creating TFM an virtual fonts for pdfLaTeX.

To use a font by its name, one can just drop it into her

/texmf/ tree and doesn't have to install it as a system font.

Since LuaTeX is a fully unicode-aware engine, one can freely mix languages, with only requirement that all the necessary glyphs are present in utilized fonts.

Auxiliary files like .aux , .toc , .idx etc. are human readable in contrast to pdfLaTeX (with inputenc). It helps with debugging index or PDF bookmarks.

Requires modern TeX distribution. For example, limits positioning for slanted math operators (like integrals) was fixed only in version 1.0 (TeXlive 2016 has 0.95).

Русский язык в TeX(LaTeX)

Добрый день. Установил texlive, texlive-full и начал изучать LaTeX.Почитал глав 8 в книге и понял, что это не мое. Конечно вещь замечательная, но я не пойму, как она все это делает. Сначала выбираешь тип документа, потом подключаешь языковые пакеты и остальную фигню. Получается куча строк ни о чем. Чтобы что-то сделать, нужно идти в гугл и искать там решение. Не хватило моих дотошных нервов на долго. Я нашел книгу Кнута про TeX и начал ее штудировать. В итоге понимаю, что долго я не выдержу, не смогу писать скучные примеры на английском. Так как я периодически пишу статьи для блога, решил для тренировки оформлять их в TeX. Так нет блин! LaTeX русский язык понимает, а он - нет. Код такой

This is TeX, Version 3.1415926 (TeX Live 2012/Debian) (./TeX.tex ! Undefined control sequence. l.1 \usepackage [utf8]

Так это что получается usepackage не существует в TeX? Как в нем использовать русские буквы, кавычки и т.д? А найти что-то про TeX в google невозможно, там все о LaTeX. Вот например. Зная c++, можно реализовать нужный алгоритм. Мне не требуется что-то подключать, чтобы работать с циклами или чем-то другим. Вообще, как изучать TeX/LaTeX и понимать что ты делаешь? Бесспорно переносы, типы шрифтов - это ясно. Но эти пакеты в преамбуле меня вымораживают. В книгах написано: выберите тип документа следующей строкой.

А ведь можно еще многое здесь настроить: формат бумаги, ориентацию, а как - фиг узнаешь пока не столкнешься. Тот же пакет geometry. А этот извращенный способ с русскими шрифтами в LaTeX

Похожие статьи