Выравнивание («рваное» по правому/левому краю, по центру) всех таблиц в документе

Выравнивание («рваное» по правому/левому краю, по центру) всех таблиц в документе

Предположим, я хочу выровнять все таблицы по левому краю по определенной вертикальной линии (MWE):

\documentclass[11pt,a4paper,oneside]{memoir}

\pagestyle{plain}

\usepackage{fontspec}
%\usepackage{changepage}

\setmainfont[Mapping=tex-text]{Liberation Serif}
\setsansfont[Mapping=tex-text]{Liberation Sans}
\setmonofont[Mapping=tex-text]{Liberation Mono}

\newcommand{\leftpadding}{1cm}

\begin{document}

    \chapter{}

    All Gaul is divided into three parts, one of which the Belgae inhabit, the Aquitani another, those who in their own language are called Celts, in our Gauls, the third. All these differ from each other in language, customs and laws. The river Garonne separates the Gauls from the Aquitani; the Marne and the Seine separate them from the Belgae. 

    \medskip\begin{adjustwidth}{\leftpadding}{0cm}
        \raggedright{Caption}\\
        \renewcommand*{\arraystretch}{1.4}
        \footnotesize\begin{tabular}[c]{|c|c|}

            \hline
            {Alfa}
            & {Bravo}
            \\\hline

            {Charlie}
            & {Delta}
            \\\hline

        \end{tabular}
    \end{adjustwidth}

    \bigskip
    Of all these, the Belgae are the bravest, because they are furthest from the civilization and refinement of [our] Province, and merchants least frequently resort to them, and import those things which tend to effeminate the mind.

    \medskip\begin{adjustwidth}{\leftpadding}{0cm}
        \raggedright{Another Caption}\\
        \renewcommand*{\arraystretch}{1.4}
        \footnotesize\begin{tabular}[c]{|c|c|}

            \hline
            {Longer Echo}
            & {Long Foxtrot}
            \\\hline

            {Golf}
            & {Hotel}
            \\\hline

        \end{tabular}
    \end{adjustwidth}

    \bigskip
    They are the nearest to the Germans, who dwell beyond the Rhine, with whom they are continually waging war; for which reason the Helvetii also surpass the rest of the Gauls in valor.

\end{document}

Это решение работает, но мне нужно больше гибкости. Как, например, мне переопределить, \leftpaddingчтобы центрировать все таблицы одновременно? Это должно быть возможно, по крайней мере, в два прохода. Возможность выравнивания по правому краю тоже не помешала бы. Также приветствуются совершенно разные решения для одной и той же цели.

решение1

Хотя я не совсем понимаю, что вы хотите, вот решение (которое, надеюсь, соответствует вашим потребностям) с использованием -package pgfkeys. Я сделал подписи таким образом, что их можно пометить (используя ключ label=), но они не используют \captionкоманду внутри. Также он использует не вашу команду, \leftpaddingа paddingключ -.

\documentclass[11pt,a4paper,oneside]{memoir}

\pagestyle{plain}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
%\usepackage{fontspec}
%\usepackage{changepage}

%\setmainfont[Mapping=tex-text]{Liberation Serif}
%\setsansfont[Mapping=tex-text]{Liberation Sans}
%\setmonofont[Mapping=tex-text]{Liberation Mono}

\usepackage{pgfkeys}
\makeatletter
\newif\if@placedleft
\newif\if@placedright
\newif\if@placedmiddle
\newif\if@placedcapused
\newif\if@placedscapused
\newif\if@placedlabused
\newdimen\@placedpadding
\newdimen\@placedrest
\pgfkeys{/placedt/.is family,/placedt,
    default/.style={% change the default settings here
        place=left,
        stretch=1.4,
        padding=1cm,
    },
    stretch/.estore in=\arraystretch,
    place/.is choice,
        place/left/.code=\@placedlefttrue\@placedrightfalse\@placedmiddlefalse,
        place/right/.code=\@placedrighttrue\@placedleftfalse\@placedmiddlefalse,
        place/middle/.code=\@placedmiddletrue\@placedleftfalse\@placedrightfalse,
    padding/.estore in=\@placedpadding,
    caption/.code=\@placedcapusedtrue\def\@placedcap{#1},
    scaption/.code=\@placedscapusedtrue\def\@placedscap{#1},
    label/.code=\@placedlabusedtrue\def\@placedlab{#1},
}

\newenvironment{placedtabular}[2][]{%
    \par\medskip\noindent\begin{minipage}{\textwidth}%
        \pgfkeys{/placedt, default, #1}%
        \if@placedleft%
            \@placedrest=\textwidth%
            \advance\@placedrest by -\@placedpadding%
            \hskip\@placedpadding%
            \begin{minipage}{\@placedrest}%
                \raggedright%
        \else\if@placedmiddle%
            \centering%
        \else\if@placedright%
            \@placedrest=\textwidth%
            \advance\@placedrest by -\@placedpadding%
            \begin{minipage}{\@placedrest}%
                \raggedleft%
        \fi\fi\fi%
        \if@placedcapused%
            \refstepcounter{table}%
            \tablename~\thetable: \@placedcap%
            \if@placedscapused%
                \addcontentsline{lot}{table}{\@placedscap}%
            \else%
                \addcontentsline{lot}{table}{\@placedcap}%
            \fi%
            \if@placedlabused%
                \label{\@placedlab}%
            \fi%
            \\[0.2\baselineskip]%
        \fi%
        \footnotesize\begin{tabular}{#2}%
    }{
        \end{tabular}%
        \if@placedmiddle\else%
            \end{minipage}%
        \fi%
    \end{minipage}%
    }
\makeatother

\newcommand{\leftpadding}{1cm}

\begin{document}
\listoftables

    \chapter{}

    All Gaul is divided into three parts, one of which the Belgae inhabit, the Aquitani another, those who in their own language are called Celts, in our Gauls, the third. All these differ from each other in language, customs and laws. The river Garonne separates the Gauls from the Aquitani; the Marne and the Seine separate them from the Belgae. 

    \begin{placedtabular}[caption=Caption,label=tab:first]{|c|c|}
            \hline
            {Alfa}
            & {Bravo}
            \\\hline

            {Charlie}
            & {Delta}
            \\\hline
    \end{placedtabular}

    \medskip\begin{adjustwidth}{\leftpadding}{0cm}
        \raggedright{Caption}\\
        \renewcommand*{\arraystretch}{1.4}
        \footnotesize\begin{tabular}[c]{|c|c|}

            \hline
            {Alfa}
            & {Bravo}
            \\\hline

            {Charlie}
            & {Delta}
            \\\hline

        \end{tabular}
    \end{adjustwidth}

    \bigskip
    Of all these, the Belgae are the bravest, because they are furthest from the civilization and refinement of [our] Province, and merchants least frequently resort to them, and import those things which tend to effeminate the mind.

    \begin{placedtabular}[caption=Another Caption,label=tab:second]{|c|c|}
            \hline
            {Longer Echo}
            & {Long Foxtrot}
            \\\hline

            {Golf}
            & {Hotel}
            \\\hline
    \end{placedtabular}
    \medskip\begin{adjustwidth}{\leftpadding}{0cm}
        \raggedright{Another Caption}\\
        \renewcommand*{\arraystretch}{1.4}
        \footnotesize\begin{tabular}[c]{|c|c|}

            \hline
            {Longer Echo}
            & {Long Foxtrot}
            \\\hline

            {Golf}
            & {Hotel}
            \\\hline

        \end{tabular}
    \end{adjustwidth}

    \bigskip
    They are the nearest to the Germans, who dwell beyond the Rhine, with whom they are continually waging war; for which reason the Helvetii also surpass the rest of the Gauls in valor.

\end{document}

EDIT: Обратите внимание, что я немного изменил приведенный выше код.

Использование -environment placedtabularтакое же, как и обычное tabular, за исключением того, что в необязательном аргументе можно использовать key=valueсинтаксис, разделенный запятыми. Следующие ключи являются доступными:

  • stretch: значение, используемое дляarraystretch
  • place: размещение таблицы. Доступны left, rightиmiddle
  • padding: пространство слева или справа с place=leftили place=right, соответственно
  • caption: заголовок, используемый для таблицы
  • scaption: имя-таблицы для \listoftables, если не используется, то captionиспользуется. Если captionне используется, то это не имеет никакого эффекта.
  • label: метка, используемая для ссылки на таблицу

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

Из вышеупомянутых ключей placeи stretchимеют paddingзначение по умолчанию, которое устанавливается в скобках, default/.style={...}которые используются внутри первого вызова \pgfkeysв MWE выше. Также есть комментарий 'измените настройки по умолчанию здесь'.

EDIT2: Код ниже - это все, что находится между \makeatletterи \makeatotherи не устанавливает 'table xy' перед заголовком. Из-за этого я также удалил -key, labelтак как ссылки не будут работать с этим.

\makeatletter
\newif\if@placedleft
\newif\if@placedright
\newif\if@placedmiddle
\newif\if@placedcapused
\newif\if@placedscapused
%\newif\if@placedlabused
\newdimen\@placedpadding
\newdimen\@placedrest
\pgfkeys{/placedt/.is family,/placedt,
    default/.style={%
        place=left,
        stretch=1.4,
        padding=1cm,
    },
    stretch/.estore in=\arraystretch,
    place/.is choice,
        place/left/.code=\@placedlefttrue\@placedrightfalse\@placedmiddlefalse,
        place/right/.code=\@placedrighttrue\@placedleftfalse\@placedmiddlefalse,
        place/middle/.code=\@placedmiddletrue\@placedleftfalse\@placedrightfalse,
    padding/.estore in=\@placedpadding,
    caption/.code=\@placedcapusedtrue\def\@placedcap{#1},
    scaption/.code=\@placedscapusedtrue\def\@placedscap{#1},
}

\newenvironment{placedtabular}[2][]{%
    \par\medskip\noindent\begin{minipage}{\textwidth}%
        \pgfkeys{/placedt, default, #1}%
        \if@placedleft%
            \@placedrest=\textwidth%
            \advance\@placedrest by -\@placedpadding%
            \hskip\@placedpadding%
            \begin{minipage}{\@placedrest}%
                \raggedright%
        \else\if@placedmiddle%
            \centering%
        \else\if@placedright%
            \@placedrest=\textwidth%
            \advance\@placedrest by -\@placedpadding%
            \begin{minipage}{\@placedrest}%
                \raggedleft%
        \fi\fi\fi%
        \if@placedcapused%
            \@placedcap%
            \if@placedscapused%
                \addcontentsline{lot}{table}{\@placedscap}%
            \else%
                \addcontentsline{lot}{table}{\@placedcap}%
            \fi%
            \\[0.2\baselineskip]%
        \fi%
        \footnotesize\begin{tabular}{#2}%
  }{
      \end{tabular}%
      \if@placedmiddle\else%
          \end{minipage}%
      \fi%
  \end{minipage}%
  }

\makeatother

EDIT3: Полный код (без префикса labelи без него Table x.y:), который включает еще две опции:

  • fontприменяются ли к таблице переключатели шрифтов (например \bfseries, , \footnotesizeили \small)
  • captionfontприменены ли переключатели шрифтов к заголовку

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

\documentclass[11pt,a4paper,oneside]{memoir}

\pagestyle{plain}

\usepackage{fontspec}
%\usepackage{changepage}

\setmainfont[Mapping=tex-text]{Liberation Serif}
\setsansfont[Mapping=tex-text]{Liberation Sans}
\setmonofont[Mapping=tex-text]{Liberation Mono}

\usepackage{pgfkeys}
\makeatletter
\newif\if@placedleft
\newif\if@placedright
\newif\if@placedmiddle
\newif\if@placedcapused
\newif\if@placedscapused
\newif\if@placedfontused
\newif\if@placedcfontused
\newdimen\@placedpadding
\newdimen\@placedrest
\pgfkeys{/placedt/.is family,/placedt,
    default/.style={%
        place=left,
        stretch=1.4,
        padding=1cm,
    },
    stretch/.estore in=\arraystretch,
    place/.is choice,
        place/left/.code=\@placedlefttrue\@placedrightfalse\@placedmiddlefalse,
        place/right/.code=\@placedrighttrue\@placedleftfalse\@placedmiddlefalse,
        place/middle/.code=\@placedmiddletrue\@placedleftfalse\@placedrightfalse,
    padding/.estore in=\@placedpadding,
    caption/.code=\@placedcapusedtrue\def\@placedcap{#1},
    scaption/.code=\@placedscapusedtrue\def\@placedscap{#1},
    font/.store in=\@placedfont,
    captionfont/.store in=\@placedcapfont,
    font/.code=\@placedfontusedtrue\def\@placedfont{#1},
    captionfont/.code=\@placedcfontusedtrue\def\@placedcapfont{#1},
}

\newenvironment{placedtabular}[2][]{%
    \par\medskip\noindent\begin{minipage}{\textwidth}%
        \pgfkeys{/placedt, default, #1}%
        \if@placedleft%
            \@placedrest=\textwidth%
            \advance\@placedrest by -\@placedpadding%
            \hskip\@placedpadding%
            \begin{minipage}{\@placedrest}%
                \raggedright%
        \else\if@placedmiddle%
            \centering%
        \else\if@placedright%
            \@placedrest=\textwidth%
            \advance\@placedrest by -\@placedpadding%
            \begin{minipage}{\@placedrest}%
                \raggedleft%
        \fi\fi\fi%
        \if@placedcapused%
            {\if@placedcfontused\normalsize\normalfont\@placedcapfont\fi\@placedcap}%
            \if@placedscapused%
                \addcontentsline{lot}{table}{\@placedscap}%
            \else%
                \addcontentsline{lot}{table}{\@placedcap}%
            \fi%
            \\[0.2\baselineskip]%
        \fi%
        \if@placedfontused\normalsize\normalfont\@placedfont\fi%
        \begin{tabular}{#2}%
    }{
        \end{tabular}%
        \if@placedmiddle\else%
            \end{minipage}%
        \fi%
    \end{minipage}%
    }
\makeatother

\newcommand{\leftpadding}{1cm}

\begin{document}
\listoftables

    \chapter{}

    All Gaul is divided into three parts, one of which the Belgae inhabit, the Aquitani another, those who in their own language are called Celts, in our Gauls, the third. All these differ from each other in language, customs and laws. The river Garonne separates the Gauls from the Aquitani; the Marne and the Seine separate them from the Belgae. 

    \begin{placedtabular}[caption=Caption,font=\bfseries]{|c|c|}
            \hline
            {Alfa}
            & {Bravo}
            \\\hline

            {Charlie}
            & {Delta}
            \\\hline
    \end{placedtabular}

    \medskip\begin{adjustwidth}{\leftpadding}{0cm}
        \raggedright{Caption}\\
        \renewcommand*{\arraystretch}{1.4}
        \footnotesize\begin{tabular}[c]{|c|c|}

            \hline
            {Alfa}
            & {Bravo}
            \\\hline

            {Charlie}
            & {Delta}
            \\\hline

        \end{tabular}
    \end{adjustwidth}

    \bigskip
    Of all these, the Belgae are the bravest, because they are furthest from the civilization and refinement of [our] Province, and merchants least frequently resort to them, and import those things which tend to effeminate the mind.

    \begin{placedtabular}[caption={Another\protect\\Caption}]{|c|c|}
            \hline
            {Longer Echo}
            & {Long Foxtrot}
            \\\hline

            {Golf}
            & {Hotel}
            \\\hline
    \end{placedtabular}
    \begin{placedtabular}[caption=Another Caption]{|c|c|}
            \hline
            {Longer Echo}
            & {Long Foxtrot}
            \\\hline

            {Golf}
            & {Hotel}
            \\\hline
    \end{placedtabular}
    \medskip\begin{adjustwidth}{\leftpadding}{0cm}
        \raggedright{Another Caption}\\
        \renewcommand*{\arraystretch}{1.4}
        \footnotesize\begin{tabular}[c]{|c|c|}

            \hline
            {Longer Echo}
            & {Long Foxtrot}
            \\\hline

            {Golf}
            & {Hotel}
            \\\hline

        \end{tabular}
    \end{adjustwidth}

    \bigskip
    They are the nearest to the Germans, who dwell beyond the Rhine, with whom they are continually waging war; for which reason the Helvetii also surpass the rest of the Gauls in valor.

\end{document}

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