Автоматическая индексация ссылок по автору и году

Автоматическая индексация ссылок по автору и году

Я пишу обзор литературы и хотел бы добавить индексы как по авторам, так и по году публикации (т. е. дваотдельныйindexes). Теперь я мог бы вручную вводить соответствующие \index{}команды, но, похоже, это то, что biblatex может делать автоматически. Это, безусловно, значительно облегчило бы обслуживание, что является важным соображением, поскольку я намерен поддерживать обзор в актуальном состоянии в течение следующих нескольких лет по мере продвижения моих исследований.

Я играл с опцией индексации, встроенной в biblatex, но не могу понять, как заставить ее работать с несколькими индексами (или даже с индексом по одному году, если на то пошло). Аналогично, я рассматривал такие вопросы, какВот этотпо написанию пользовательских \citeкоманд, но мне сложно понять, как они работают.

Минимальный рабочий пример с ручной индексацией (с использованием biblatex и multind), демонстрирующий тот конечный результат, который мне нужен:

\documentclass{report}

\usepackage{filecontents}
\begin{filecontents*}{testing.bib}
@article{Author2010,
    author="Author, A and Writer, B",
    journal="Slackers Monthly",
    title="An overly long treatise on procrastination",
    year=2010,
    month=jun,
}
@article{Writer2011,
    author="Writer, B and Scribe, C",
    journal="Fake Online Journal",
    title="Waste of time or time of waste: procrastination in a modern society",
    year=2011,
    month=oct,
}
@book{Writer2003,
    author="Writer, B",
    title="Procrastination for dummies",
    year=2003,
    publisher="Procrastination House",
    address="Auckland",
}
\end{filecontents*}

\usepackage[style=authoryear]{biblatex}
\addbibresource{testing}

\usepackage{multind}
\makeindex{authors}
\makeindex{years}

\begin{document}

\chapter{Introductory works}

\section{An overly long treatise on procrastination}

\fullcite{Author2010}
\index{authors}{Author, A!An overly long treatise on procrastination (2010)}
\index{authors}{Writer, B!An overly long treatise on procrastination (2010)}
\index{years}{2010!An overly long treatise on procrastination}

This paper was really useful in telling me how to waste more time rather 
than doing real work.

\section{Waste of time or time of waste: procrastination in a modern society}

\fullcite{Writer2011}
\index{authors}{Writer, B!Waste of time or time of waste: procrastination in a modern society (2011)}
\index{authors}{Scribe, C!Waste of time or time of waste: procrastination in a modern society (2011)}
\index{years}{2011!Waste of time or time of waste: procrastination in a modern society}

Applies post-modern philosophical theory to procrastination.

\section{Procrastination for dummies}

\fullcite{Writer2003}
\index{authors}{Writer, B!Procrastination for dummies (2003)}
\index{years}{2003!Procrastination for dummies}

A classic reference book for anybody starting a research position.

\printbibliography
\printindex{authors}{Author index}
\printindex{years}{Year index}

\end{document}

И Makefile для его компиляции:

default:
    xelatex mwe
    bibtex mwe
    xelatex mwe
    xindy -M texindy -M page-ranges -L english -C utf8 authors.idx
    xindy -M texindy -M page-ranges -L english -C utf8 years.idx
    xelatex mwe

Так возможно ли это сделать с помощью пользовательской команды cite (или встроенной, если на то пошло)? Или мне лучше написать скрипт для разбора вывода BibTeX/biber, чтобы сгенерировать ввод для xindy?

решение1

Этот ответ был обновлен в свете, в частности, проницательных комментариев Одри.

Да. Есть несколько способов сделать это.

Код ниже — это переработанный вариант моего первоначального предложения, который (я надеюсь) исправляет различные недостатки в его общем использовании. А именно:

  • Мой исходный код не справлялся с пустыми годами должным образом, а этот справляется.

  • Мой исходный код «зашил» multindсинтаксис и выбранные вами имена индексов: в этой версии имена индексов находятся в макросах, что означает, что их можно изменять.

  • indexsorttitleВ моем исходном коде поля и не использовались indextitle: здесь они используются, как и должно быть.

  • Мой исходный код мог вызвать проблемы с некоторыми макросами (например, \TeXиспользуемыми в indextitles, как правильно указала Одри). Надеюсь, этот код справляется с ними должным образом.

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

Как ни странно, \fullciteпохоже, что макросы индексации не вызываются, поэтому я и использовал \cite; полагаю, этому есть объяснение, но у меня нет времени вникать в него.

\documentclass{report}

\usepackage{filecontents}
\begin{filecontents*}{testing.bib}
@article{Author2010,
    author="Author, A and Writer, B",
    journal="Slackers Monthly",
    title="An overly long treatise on procrastination",
    year=2010,
    month=jun,
}
@article{Writer2011,
    author="Writer, B and Scribe, C",
    journal="Fake Online Journal",
    title="Waste of time or time of waste: procrastination in a modern society",
    year=2011,
    month=oct,
}
@book{Writer2003,
    author="Writer, B",
    title="Procrastination for dummies",
    year=2003,
    publisher="Procrastination House",
    address="Auckland",
}
@book{knuth:ct:b,
  hyphenation = {american},
  sortyear = {1986-1},
  sorttitle = {Computers & Typesetting B},
  indexsorttitle = {TeX: The Program},
  author = {Knuth, Donald E.},
  title = {\TeX: The Program},
  shorttitle = {\TeX},
  maintitle = {Computers \& Typesetting},
  volume = {B},
  publisher = {Addison-Wesley},
  location = {Reading, Mass.},
  date = {1986},
  annotation = {The second volume of a five-volume book. Note the
    \texttt{sorttitle} and \texttt{sortyear} fields. Also note the
    \texttt{indexsorttitle} field}
}
@book{yearless,
  author = {Lazy B. Ugger},
  title  = {I Can't Be Bothered with Years},
  publisher = {Equally Lazee},
}
\end{filecontents*}

\usepackage[style=authoryear,indexing=cite]{biblatex}
\addbibresource{testing.bib}
\makeatletter
% For the "years" index, we redefine the ordinary bibmacro
% which indexes titles, so that it indexes into the years
% index instead
\renewbibmacro*{index:title}[2]{%
  \iffieldundef{year}
     {\usebibmacro{index:years}%
      {\index}%
      {\undated}%
      {\thefield{indexsorttitle}}%
      {\thefield{entrykey}}}
    {\usebibmacro{index:years}%
      {\index}%
      {\thefield{year}}%
      {\thefield{indexsorttitle}}%
      {\thefield{entrykey}}}}

\newbibmacro*{index:years}[4]{%
    \begingroup
     \protected@edef\theindexentry{%
      \unexpanded{#1}\yearsindex{#2!#3\actualoperator\unexpanded{\citefield}{#4}{indextitle}}}%
     \theindexentry
     \endgroup}

% For authors we just redefine the field format (so that it
% includes title and year information
\DeclareIndexNameFormat{default}{%
  \iffieldundef{year}
    {\usebibmacro{index:name}%
      {\index}%
      {#1}%
      {#3}%
      {#5}%
      {#7}%
      {\thefield{indexsorttitle}}%
      {\thefield{entrykey}}%
      {}}
   {\usebibmacro{index:name}%
      {\index}%
      {#1}%
      {#3}%
      {#5}%
      {#7}%
      {\thefield{indexsorttitle}}%
      {\thefield{entrykey}}%
      { (\thefield{year})}}}
% ... and modify the relevant bibmacro to add the extra information
\renewbibmacro*{index:name}[8]{%
  \begingroup
  \ifuseprefix
    {\protected@edef\theindexentry{%
       \unexpanded{#1}\authorsindex{%
         \ifblank{#4}{}{#4 }%
         \@firstofone #2% remove spurious braces
         \ifblank{#5}{}{ #5}%
         \ifblank{#3}{}{, #3}%
         \actualoperator
         \ifblank{#4}{}{\MakeCapital{#4} }%
         #2%
         \ifblank{#5}{}{ #5}%
         \ifblank{#3}{}{, #3}!#6
            \actualoperator\unexpanded{\citefield}{indextitle}#8}}}%
    {\protected@edef\theindexentry{%
       \unexpanded{#1}\authorsindex{%
         \@firstofone #2% remove spurious braces
         \ifblank{#5}{}{ #5}%
         \ifblank{#3#4}{}{,}%
         \ifblank{#3}{}{ #3}%
         \ifblank{#4}{}{ #4}!#6\actualoperator
            \unexpanded{\citefield}{#7}{indextitle}#8}}}%
  \theindexentry
  \endgroup}
\makeatother
% redefine this if the index for years is differently named, or if using
% index or imakeidx
\newcommand{\yearsindex}{{years}}

% redefine this if the index for authors is differently named, or if
% using index or imakeidx
\newcommand{\authorsindex}{{authors}}

% undated entries
\newcommand{\undated}{n.d.}

\usepackage{multind}
\makeindex{authors}
\makeindex{years}

\begin{document}

\chapter{Introductory works}

\section{An overly long treatise on procrastination}

\fullcite{Author2010}

This paper was really useful in telling me how to waste more time rather 
than doing real work.

\section{Waste of time or time of waste: procrastination in a modern society}

\cite{Writer2011}

Applies post-modern philosophical theory to procrastination.

\section{Procrastination for dummies}

\cite{Writer2003}

A classic reference book for anybody starting a research position.

\section{The Awkward Squad}

\cite{knuth:ct:b}

An author who uses a title that indexing programs find hard to cope
with, but certainly no procrastinator.

\cite{yearless}

An author so lazy that he cannot be bothered to put a year of publication.


\printbibliography
\printindex{authors}{Author index}
\printindex{years}{Year index}

\end{document}

(Если вам нужно, вы можете уговорить biblatex выполнить очень сложную индексацию: я только что закончил первую версию стиля, который может создавать очень много индексов (более 33!), и который индексирует не только на основе полей заголовков, но и использует примечания для задания подпунктов. Это не так уж и сложно настраивать, но в том виде, в котором это есть в biblatex, это абсолютно выполнимо.)

решение2

Благодаря запросу на функцию от Maieul и отзыву от Paul, в 2.3 был введен ряд вспомогательных команд и макросов biblatexдля помощи в индексировании, в частности индексировании с оператором subentry !. Пример 22 из документации ( 22-indexing-subentry.tex) демонстрирует несколько индексов с subentry с использованием imakeidxпакета. Вот аналогичный пример с использованием multind.

\documentclass{article}
\usepackage[american]{babel}
\usepackage{csquotes}
\usepackage[indexing=cite,style=authoryear,backend=bibtex]{biblatex}

% Define indices
\usepackage{multind}
\makeindex{authors}
\makeindex{years}

% Name indexing directive for names with title subentries
\DeclareIndexNameFormat{name:title}{%
  \iffieldundef{title}
    {\usebibmacro{index:name}{\index{authors}}{#1}{#3}{#5}{#7}}
    {\usebibmacro{index:name:title:year}{\index{authors}}{#1}{#3}{#5}{#7}}}

% Based on index:name:title macro defined in biblatex.def, takes the arguments:
%   {<index command>}{<last name>}{<first name>}{<first initials>}{<last name prefix>}
% The index:name:subentry macro (also defined in biblatex.def) takes two more:
%   {<plain entry>}{<formatted entry>}
% and forms the subentry: !<plain entry>@<formatted entry>
\newbibmacro*{index:name:title:year}[5]{%
  \iffieldundef{year}
    {\usebibmacro{index:name:title}{#1}{#2}{#3}{#4}{#5}}
    {\usebibmacro{index:name:subentry}{#1}{#2}{#3}{#4}{#5}
       {\thefield{indexsorttitle}}
       {\emph{\csfield{indextitle}}~(\thefield{labelyear})}}}

% Title indexing directive for years with title subentries
\DeclareIndexFieldFormat{year:title}{%
  \iffieldundef{year}
    {\usebibmacro{index:entry}{\index{years}}{%
       \mkbibindexentry{0}{Not dated}%
       \subentryoperator%
       \mkbibindexfield{\thefield{indexsorttitle}}{\emph{#1}}}}
    {\usebibmacro{index:entry}{\index{years}}{%
       \thefield{year}\subentryoperator%
       \mkbibindexfield{\thefield{indexsorttitle}}{\emph{#1}}}}}

\renewbibmacro*{citeindex}{%
  \ifciteindex
    {\indexnames[name:title]{author}%
     \indexfield[year:title]{indextitle}}
    {}}

% Index entries accessed via \fullcite
\DeclareCiteCommand{\fullcite}
  {\usebibmacro{prenote}}
  {\usebibmacro{citeindex}%
   \usedriver
     {\DeclareNameAlias{sortname}{default}}
     {\thefield{entrytype}}}
  {\multicitedelim}
  {\usebibmacro{postnote}}

\addbibresource{biblatex-examples.bib}

\begin{document}
\fullcite{knuth:ct,knuth:ct:a,knuth:ct:c,knuth:ct:d}
\cite{aristotle:anima,aristotle:poetics,aristotle:physics,aristotle:rhetoric}
\printbibliography
\raggedright
\printindex{authors}{Author and Title Index}
\printindex{years}{Year and Title Index}
\end{document}

решение3

Я использую скрипт python для похожей проблемыhttp://geekographie.maieul.net/Un-index-des-sources-primaires-3.

Я просто открываю тикет, чтобы спросить о возможности индексации более одного поля.https://github.com/plk/biblatex/issues/31

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