Как улучшить внешний вид выровненного машинописного текста на мини-странице

Как улучшить внешний вид выровненного машинописного текста на мини-странице

Рассмотрим код:

\documentclass[12pt]{book}
\usepackage{microtype}
%\usepackage{ragged2e} 

\begin{document}
\thispagestyle{empty}

\begin{center}
\begin{LARGE}
\begin{minipage}{5.75in}\leftskip\fill\rightskip-\leftskip\parfillskip\stretch{2}%
\textbf{This is a minipage. The above line of commands justifies the text and centers the last line. Notice how "nice" it appears.}
\end{minipage}
\end{LARGE}
\end{center}

\vspace*{25pt}

\begin{center}
\begin{LARGE}
\begin{minipage}{5.75in}\leftskip\fill\rightskip-\leftskip\parfillskip\stretch{2}%
\spaceskip1em plus 1em \xspaceskip 1em plus 2em\relax
\texttt{I have, with the two above lines of commands, been able to justify the tttext in this minipage, as well as center the last line of output. This is what I want; however, the appearance does not seem as "nice" as the content of the above minipage.}
\end{minipage}
\end{LARGE}
\end{center}
\end{document}

который производит

введите описание изображения здесь

Хотя вторая мини-страница выдает то, что я ищу — текст, выровненный по левому и правому краю, с последней строкой вывода, выровненной по центру, — ее внешний вид кажется бледным по сравнению с выровненным выводом первой мини-страницы.

Я думал, что это можно сделать, вызвав ragged2eпакет; но после этого, помимо центрирования последней строки textttтекста, ситуация стала намного хуже.

ВОПРОС: Как я могу (просто, если это возможно) улучшить внешний вид textttвыровненного по ширине текста (например, уменьшить интервал между строками, уменьшить интервал между словами, чтобы сократить количество строк вывода)?

Я компилирую код с помощьюlualatex

Спасибо.

решение1

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

lvmtt по умолчанию допускает расстановку переносов и переменные межсловные интервалы, поэтому требуется меньше настроек.

\documentclass[12pt]{book}
\usepackage{microtype}
%\usepackage{ragged2e} 

\begin{document}
\thispagestyle{empty}

\begin{center}
\begin{LARGE}
\begin{minipage}{5.75in}\leftskip\fill\rightskip-\leftskip\parfillskip\stretch{2}%
  \textbf{This is a minipage. The above line of commands justifies the
    text and centers the last line. Notice how "nice" it appears.}
\end{minipage}
\end{LARGE}
\end{center}

\vspace*{25pt}

\begin{center}
\begin{LARGE}
\begin{minipage}{5.75in}\leftskip\fill\rightskip-\leftskip\parfillskip\stretch{2}%
    \fontfamily{lmvtt}\selectfont
    I
    have, with the two above lines of commands, been able to justify
    the tttext in this minipage, as well as center the last line of
    output. This is what I want; however, the appearance does not seem
    as "nice" as the content of the above minipage.
\end{minipage}
\end{LARGE}
\end{center}
\end{document}

Сегодня нет изображения, носм. вывод здесь

решение2

В русле вышеприведенных комментариев, это похожий, но другой подход:

Использовать \DeclareFontFamily{OT1}{cmtt}{\hyphenchar \font=1}в преамбуле. (Шрифт=1 позволяет использовать тире при переносе; шрифт=-1 разрешает перенос, но без тире.)

Кроме того, уменьшение размера шрифта также должно улучшить эстетику.

Теперь код

\documentclass[12pt]{book}
\usepackage{microtype}
\DeclareFontFamily{OT1}{cmtt}{\hyphenchar \font=1}

\begin{document}
\thispagestyle{empty}

\begin{center}
\begin{LARGE}
\begin{minipage}{5.75in}\leftskip\fill\rightskip-\leftskip\parfillskip\stretch{2}%
\textbf{This is a minipage. The above line of commands justifies the text and centers the last line. Notice how "nice" it appears.}
\end{minipage}
\end{LARGE}
\end{center}

\vspace*{25pt}

\begin{center}
\begin{large}
\begin{minipage}{5.75in}\leftskip\fill\rightskip-\leftskip\parfillskip\stretch{2}%
\spaceskip1em plus 1em \xspaceskip 1em plus 2em\relax
\texttt{This is a minipage. The above line of commands justifies the text and centers the last line. Notice how "nice" it appears.}
\end{minipage}
\end{large}
\end{center}

\vspace*{25pt}

\begin{center}
\begin{large}
\begin{minipage}{5.75in}\leftskip\fill\rightskip-\leftskip\parfillskip\stretch{2}%
\spaceskip1em plus 1em \xspaceskip 1em plus 2em\relax
\texttt{This is a minipage. Supercalifragilisticexpialidocious Supercalifragilisticexpialidocious Supercalifragilisticexpialidocious Supercalifragilisticexpialidocious Supercalifragilisticexpialidocious}
\end{minipage}
\end{large}
\end{center}
\end{document}

выдает результат:

введите описание изображения здесь

Поскольку во втором абзаце переносить было нечего, я добавил третий, чтобы проиллюстрировать, что кодделаетпроизводить переносы.

решение3

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

Такие шрифты обычно не допускают переносов, отключая \hyphencharдля них. С pdflatexи шрифтами по умолчанию в кодировке OT1 мы можем прочитать, ot1cmtt.fdчтобы увидеть

\ProvidesFile{ot1cmtt.fd}
        [2019/12/16 v2.5j Standard LaTeX font definitions]
\DeclareFontFamily{OT1}{cmtt}{\hyphenchar \font\m@ne}
\DeclareFontShape{OT1}{cmtt}{m}{n}
     {%
      <5><6><7><8>cmtt8<9>cmtt9%
      <10><10.95>cmtt10%
      <12><14.4><17.28><20.74><24.88>cmtt12%
      }{}
[...]

и \m@neозначает -1. Большинство шрифтов не будут иметь \hyphencharобъявления, поскольку в этом случае TeX будет использовать \defaulthyphenchar, который содержит значение 45 (слот шрифта для дефиса). Значения для межсловных пробелов вместо этого хранятся в файле .tfm, и вы можете изменить их, воздействуя на соответствующие \fontdimenпараметры.

Вместо этого lualatexследует tulmtt.fdиспользовать:

\ProvidesFile{tulmtt.fd}
        [2021/07/23 v1.8a Standard LaTeX font definitions for Latin Modern]
\DeclareFontFamily{TU}{lmtt}{%
\hyphenchar \font\m@ne
\fontdimen3\font\z@
\fontdimen4\font\z@
}
[...]

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

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

Я полагаю, что это не так.

\documentclass[12pt]{book}
\usepackage{microtype}

\newenvironment{monospacedquote}{%
  \begin{center}
  \begin{minipage}{5.75in}
  \LARGE
  \ttfamily
  \ifnum\hyphenchar\font=-1
    \hyphenchar\font=`-
    \fontdimen3\font=0.5\fontdimen2\font
    \fontdimen4\font=0.3\fontdimen2\font
    \fontdimen7\font=0.2\fontdimen2\font
  \fi
  \selectfont
  \leftskip=\fill
  \rightskip=-\leftskip
  \parfillskip=\stretch{2}%
}{\end{minipage}\end{center}}

\begin{document}

\begin{monospacedquote}
This is a minipage. The above line of commands justifies the text 
and centers the last line. Notice how awful it appears.
\end{monospacedquote}

\end{document}

введите описание изображения здесь

решение4

Ваша проблема в том, что вы установили большие пробелы между словами, установив \spaceskip. Я попытаюсь перефразировать ваш вопрос: "Я установил большие пробелы с помощью примитива TeX \spaceskip, почему у меня большие пробелы?"

Если вы установите меньшее количество пробелов, \spaceskipто вы получите желаемый результат. Более того, я установил hyphenchar для \ttшрифта, это упоминается здесь в других ответах тоже.

\documentclass[12pt]{book}
\usepackage{microtype}

\begin{document}
\thispagestyle{empty}

\begin{center}
\begin{LARGE}
\begin{minipage}{5.75in}\leftskip\fill\rightskip-\leftskip\parfillskip\stretch{2}%
\textbf{This is a minipage. The above line of commands justifies the text and centers the last line. Notice how "nice" it appears.}
\end{minipage}
\end{LARGE}
\end{center}

\vspace*{25pt}

\begin{center}
\begin{LARGE}
\begin{minipage}{5.75in}\leftskip\fill\rightskip-\leftskip\parfillskip\stretch{2}%
%\spaceskip1em plus 1em \xspaceskip 1em plus 2em\relax %% ??? why this?
\spaceskip.3em plus .2em minus .1em \xspaceskip=\spaceskip {\tt\hyphenchar\font=`-}%
\texttt{I have, with the two above lines of commands, been able to justify the tttext in this minipage, as well as center the last line of output. This is what I want; however, the appearance does not seem as "nice" as the content of the above minipage.}
\end{minipage}
\end{LARGE}
\end{center}
\end{document}

Связанный контент