WYSIWYG citation labels when using natbib.

git-svn-id: svn://svn.lyx.org/lyx/lyx-devel/trunk@4052 a592a061-630c-0410-9148-cb99ea01b6c8
This commit is contained in:
Angus Leeming 2002-04-24 10:00:39 +00:00
parent d90f89db7e
commit d2d18edefc
9 changed files with 444 additions and 89 deletions

View File

@ -1,3 +1,9 @@
2002-04-22 Angus Leeming <a.leeming@ic.ac.uk>
* buffer.C (getBibkeyList): If using \bibliography, return the
option field with the reference itself. Enables us to provide natbib
support when using \bibliography.
2002-04-23 Mike Ressler <mike.ressler@alum.mit.edu>
* lyxtextclass.[Ch]: add layout keyword ProvidesNatbib.

View File

@ -3701,9 +3701,14 @@ vector<pair<string, string> > const Buffer::getBibkeyList() const
vector<StringPair> keys;
Paragraph * par = paragraph;
while (par) {
if (par->bibkey)
keys.push_back(StringPair(par->bibkey->getContents(),
par->asString(this, false)));
if (par->bibkey) {
string const key = par->bibkey->getContents();
string const opt = par->bibkey->getOptions();
string const ref = par->asString(this, false);
string const info = opt + "TheBibliographyRef" + ref;
keys.push_back(StringPair(key, info));
}
par = par->next();
}

View File

@ -1,3 +1,10 @@
2002-04-22 Angus Leeming <a.leeming@ic.ac.uk>
* biblio.C (getAbbreviatedAuthor, getYear): Cæsar is dead. RIP; he was
way past his use-by date.
Make use of the improved info from Buffer::getBibkeyList when using
\bibliography. Enables us to provide natbib support in this case too.
2002-04-19 Marco Morandini <morandini@aero.polimi.it>
* ControlGraphics.C: pass the browseFile dialog a string of only those

View File

@ -175,33 +175,45 @@ string const getAbbreviatedAuthor(InfoMap const & map, string const & key)
lyx::Assert(!map.empty());
InfoMap::const_iterator it = map.find(key);
if (it == map.end())
return string();
string author;
if (it != map.end()) {
author = parseBibTeX(it->second, "author");
if (author.empty())
author = parseBibTeX(it->second, "editor");
vector<string> authors = getVectorFromString(author, "and");
if (!authors.empty()) {
author.erase();
for (vector<string>::iterator it = authors.begin();
it != authors.end(); ++it) {
*it = familyName(strip(*it));
}
author = authors[0];
if (authors.size() == 2)
author += _(" and ") + authors[1];
else if (authors.size() > 2)
author += _(" et al.");
string::size_type const pos = it->second.find("TheBibliographyRef");
if (pos != string::npos) {
if (pos <= 2) {
return string();
}
string const opt =
strip(frontStrip(it->second.substr(0, pos-1)));
if (opt.empty())
return string();
string authors;
split(opt, authors, '(');
return authors;
}
string author = parseBibTeX(it->second, "author");
if (author.empty())
author = _("Caesar et al.");
author = parseBibTeX(it->second, "editor");
vector<string> authors = getVectorFromString(author, "and");
if (!authors.empty()) {
author.erase();
for (vector<string>::iterator it = authors.begin();
it != authors.end(); ++it) {
*it = familyName(strip(*it));
}
author = authors[0];
if (authors.size() == 2)
author += _(" and ") + authors[1];
else if (authors.size() > 2)
author += _(" et al.");
}
return author;
}
@ -212,15 +224,29 @@ string const getYear(InfoMap const & map, string const & key)
lyx::Assert(!map.empty());
InfoMap::const_iterator it = map.find(key);
if (it == map.end())
return string();
string year;
string::size_type const pos = it->second.find("TheBibliographyRef");
if (pos != string::npos) {
if (pos <= 2) {
return string();
}
if (it != map.end())
year = parseBibTeX(it->second, "year");
string const opt =
strip(frontStrip(it->second.substr(0, pos-1)));
if (opt.empty())
return string();
if (year.empty())
year = "50BC";
string authors;
string const tmp = split(opt, authors, '(');
string year;
split(tmp, year, ')');
return year;
}
string year = parseBibTeX(it->second, "year");
return year;
}
@ -253,9 +279,15 @@ string const getInfo(InfoMap const & map, string const & key)
InfoMap::const_iterator it = map.find(key);
if (it == map.end())
return string();
// is the entry a BibTeX one or one from lyx-layout "bibliography"?
if (!contains(it->second,'='))
return it->second.c_str();
string const separator("TheBibliographyRef");
string::size_type const pos = it->second.find(separator);
if (pos != string::npos) {
string::size_type const pos2 = pos + separator.size();
string const info = strip(frontStrip(it->second.substr(pos2)));
return info;
}
// Search for all possible "required" keys
string author = parseBibTeX(it->second, "author");
@ -521,16 +553,15 @@ getNumericalStrings(string const & key,
InfoMap const & map, vector<CiteStyle> const & styles)
{
if (map.empty()) {
vector<string> vec(1);
vec[0] = _("No database");
return vec;
return vector<string>();
}
vector<string> vec(styles.size());
string const author = getAbbreviatedAuthor(map, key);
string const year = getYear(map, key);
if (author.empty() || year.empty())
return vector<string>();
vector<string> vec(styles.size());
for (vector<string>::size_type i = 0; i != vec.size(); ++i) {
string str;
@ -577,25 +608,24 @@ getAuthorYearStrings(string const & key,
InfoMap const & map, vector<CiteStyle> const & styles)
{
if (map.empty()) {
vector<string> vec(1);
vec[0] = _("No database");
return vec;
return vector<string>();
}
vector<string> vec(styles.size());
string const author = getAbbreviatedAuthor(map, key);
string const year = getYear(map, key);
if (author.empty() || year.empty())
return vector<string>();
vector<string> vec(styles.size());
for (vector<string>::size_type i = 0; i != vec.size(); ++i) {
string str;
switch (styles[i]) {
case CITE:
case CITET:
str = author + " (" + year + ")";
break;
case CITE:
case CITEP:
str = "(" + author + ", " + year + ")";
break;

View File

@ -3,6 +3,11 @@
* FormBibtex.C: Do not use a blank after the comma for multiple
bib-files (which is not read in correctly).
2002-04-22 Angus Leeming <a.leeming@ic.ac.uk>
* FormCitation.C (fillChoice): If the getCiteStrings vec is empty,
disable the choice.
2002-04-19 Juergen Vigna <jug@sad.it>
* FormParagraph.C (changedParagraph): don't check for p == par_ as

View File

@ -53,11 +53,17 @@ void fillChoice(FD_form_citation * dialog, vector<string> vec)
return;
// They will be changed. Proceed
string const str = " " + getStringFromVector(vec, " | ") + " ";
string str = " ";
if (!vec.empty())
str += getStringFromVector(vec, " | ") + " ";
fl_clear_choice(dialog->choice_style);
fl_addto_choice(dialog->choice_style, str.c_str());
setEnabled(dialog->choice_style, !vec.empty());
if (vec.empty())
return;
// The width of the choice varies with the contents.
// Ensure that it is centred in the frame.
@ -114,15 +120,20 @@ FormCitation::FormCitation(ControlCitation & c)
void FormCitation::apply()
{
vector<biblio::CiteStyle> const & styles =
ControlCitation::getCiteStyles();
string command = "cite";
if (dialog_->choice_style->active != 0) {
vector<biblio::CiteStyle> const & styles =
ControlCitation::getCiteStyles();
int const choice = fl_get_choice(dialog_->choice_style) - 1;
bool const full = fl_get_button(dialog_->check_full_author_list);
bool const force = fl_get_button(dialog_->check_force_uppercase);
int const choice =
fl_get_choice(dialog_->choice_style) - 1;
bool const full =
fl_get_button(dialog_->check_full_author_list);
bool const force =
fl_get_button(dialog_->check_force_uppercase);
string const command =
biblio::getCiteCommand(styles[choice], full, force);
command = biblio::getCiteCommand(styles[choice], full, force);
}
controller().params().setCmdName(command);
controller().params().setContents(getStringFromVector(citekeys));

View File

@ -1,3 +1,9 @@
2002-04-22 Angus Leeming <a.leeming@ic.ac.uk>
* insetcite.[Ch]: take Herbert's patch to give WYSIWYG citation labels
when using natbib and make it work efficiently. Must emphasise that the
real work is Herbert's.
2002-04-23 Juergen Vigna <jug@sad.it>
* insettabular.C (drawCellSelection): fix off by 1 error.

View File

@ -1,11 +1,11 @@
/* This file is part of*
* ======================================================
/**
* \file insetcite.C
* Copyright 2001 the LyX Team
* Read the file COPYING
*
* LyX, The Document Processor
*
* Copyright 2000-2001 The LyX Team.
*
* ====================================================== */
* \author Angus Leeming, a.leeming@ic.ac.uk
* \author Herbert Voss, voss@lyx.org 2002-03-17
*/
#include <config.h>
@ -18,68 +18,318 @@
#include "BufferView.h"
#include "LaTeXFeatures.h"
#include "LyXView.h"
#include "debug.h"
#include "gettext.h"
#include "frontends/controllers/biblio.h"
#include "frontends/Dialogs.h"
#include "support/filetools.h"
#include "support/lstrings.h"
#include "support/path.h"
#include "support/os.h"
#include "support/lstrings.h"
#include "support/LAssert.h"
#include <map>
using std::ostream;
using std::vector;
using std::map;
namespace {
// An optimisation. We assume that until the first InsetCitation::edit is
// called, we're loding the buffer and that, therefore, we don't need to
// reload the bibkey list
std::map<Buffer const *, bool> loading_buffer;
string const getNatbibLabel(Buffer const * buffer,
string const & citeType, string const & keyList,
string const & before, string const & after,
bool numerical)
{
// Only reload the bibkeys if we have to...
map<Buffer const *, bool>::iterator lit = loading_buffer.find(buffer);
if (lit != loading_buffer.end())
loading_buffer[buffer] = true;
typedef std::map<Buffer const *, biblio::InfoMap> CachedMap;
static CachedMap cached_keys;
CachedMap::iterator kit = cached_keys.find(buffer);
if (!loading_buffer[buffer] || kit == cached_keys.end()) {
// build the keylist
typedef vector<std::pair<string, string> > InfoType;
InfoType bibkeys = buffer->getBibkeyList();
InfoType::const_iterator bit = bibkeys.begin();
InfoType::const_iterator bend = bibkeys.end();
biblio::InfoMap infomap;
for (; bit != bend; ++bit) {
infomap[bit->first] = bit->second;
}
if (infomap.empty())
return string();
cached_keys[buffer] = infomap;
}
biblio::InfoMap infomap = cached_keys[buffer];
// the natbib citation-styles
// CITET: author (year)
// CITEP: (author,year)
// CITEALT: author year
// CITEALP: author, year
// CITEAUTHOR: author
// CITEYEAR: year
// CITEYEARPAR: (year)
string before_str;
if (!before.empty()) {
// In CITET and CITEALT mode, the "before" string is
// attached to the label associated with each and every key.
// In CITEP, CITEALP and CITEYEARPAR mode, it is attached
// to the front of the whole only.
// In other modes, it is not used at all.
if (citeType == "citet" ||
citeType == "citealt" ||
citeType == "citep" ||
citeType == "citealp" ||
citeType == "citeyearpar")
before_str = before + ' ';
}
string after_str;
if (!after.empty()) {
// The "after" key is appended only to the end of the whole.
after_str = ", " + after;
}
// One day, these might be tunable (as they are in BibTeX).
char const op = '('; // opening parenthesis.
char const cp = ')'; // closing parenthesis.
char const sep = ';'; // puctuation mark separating citation entries.
string const op_str(string(1, ' ') + string(1, op));
string const cp_str(string(1, cp) + string(1, ' '));
string const sep_str(string(1, sep) + string(1, ' '));
string label;
vector<string> keys = getVectorFromString(keyList);
vector<string>::const_iterator it = keys.begin();
vector<string>::const_iterator end = keys.end();
for (; it != end; ++it) {
// get the bibdata corresponding to the key
string const author(biblio::getAbbreviatedAuthor(infomap, *it));
string const year(biblio::getYear(infomap, *it));
// Something isn't right. Fail safely.
if (author.empty() || year.empty())
return string();
// (authors1 (<before> year); ... ;
// authors_last (<before> year, <after>)
if (citeType == "citet") {
string const tmp = numerical ? '#' + *it : year;
label += author + op_str + before_str + tmp +
cp + sep_str;
// author, year; author, year; ...
} else if (citeType == "citep" ||
citeType == "citealp") {
if (numerical) {
label += *it + sep_str;
} else {
label += author + ", " + year + sep_str;
}
// (authors1 <before> year;
// authors_last <before> year, <after>)
} else if (citeType == "citealt") {
string const tmp = numerical ? '#' + *it : year;
label += author + ' ' + before_str + tmp + sep_str;
// author; author; ...
} else if (citeType == "citeauthor") {
label += author + sep_str;
// year; year; ...
} else if (citeType == "citeyear" ||
citeType == "citeyearpar") {
label += year + sep_str;
}
}
label = strip(strip(label), sep);
if (!after_str.empty()) {
if (citeType == "citet") {
// insert "after" before last ')'
label.insert(label.size()-1, after_str);
} else {
bool const add = !(numerical &&
(citeType == "citeauthor" ||
citeType == "citeyear"));
if (add)
label += after_str;
}
}
if (!before_str.empty() && (citeType == "citep" ||
citeType == "citealp" ||
citeType == "citeyearpar")) {
label = before_str + label;
}
if (citeType == "citep" || citeType == "citeyearpar")
label = string(1, op) + label + string(1, cp);
return label;
}
string const getBasicLabel(string const & keyList, string const & after)
{
string keys(keyList);
string label;
if (contains(keys, ",")) {
// Final comma allows while loop to cover all keys
keys = frontStrip(split(keys, label, ',')) + ",";
while (contains(keys, ",")) {
string key;
keys = frontStrip(split(keys, key, ','));
label += ", " + key;
}
} else
label = keys;
if (!after.empty())
label += ", " + after;
return "[" + label + "]";
}
} // anon namespace
InsetCitation::InsetCitation(InsetCommandParams const & p, bool)
: InsetCommand(p)
{}
string const InsetCitation::getScreenLabel(Buffer const *) const
string const InsetCitation::generateLabel(Buffer const * buffer) const
{
string keys(getContents());
string const before = string();
string const after = getOptions();
// If keys is "too long" then only print out the first few tokens
string label;
if (contains(keys, ",")) {
// Final comma allows while loop to cover all keys
keys = frontStrip(split(keys, label, ',')) + ",";
string::size_type const maxSize = 40;
while (contains(keys, ",")) {
string key;
keys = frontStrip(split(keys, key, ','));
string::size_type size = label.size() + 2 + key.size();
if (size >= maxSize) {
label += ", ...";
break;
}
label += ", " + key;
if (buffer->params.use_natbib) {
string cmd = getCmdName();
if (cmd == "cite") {
// We may be "upgrading" from an older LyX version.
// If, however, we use "cite" because the necessary
// author/year info is not present in the biblio
// database, then getNatbibLabel will exit gracefully
// and we'll call getBasicLabel.
if (buffer->params.use_numerical_citations)
cmd = "citep";
else
cmd = "citet";
}
} else {
label = keys;
label = getNatbibLabel(buffer, cmd, getContents(),
before, after,
buffer->params.use_numerical_citations);
}
if (!getOptions().empty())
label += ", " + getOptions();
// Fallback to fail-safe
if (label.empty()) {
label = getBasicLabel(getContents(), after);
}
return "[" + label + "]";
return label;
}
InsetCitation::Cache::Style InsetCitation::getStyle(Buffer const * buffer) const
{
Cache::Style style = Cache::BASIC;
if (buffer->params.use_natbib) {
if (buffer->params.use_numerical_citations) {
style = Cache::NATBIB_NUM;
} else {
style = Cache::NATBIB_AY;
}
}
return style;
}
string const InsetCitation::getScreenLabel(Buffer const * buffer) const
{
Cache::Style const style = getStyle(buffer);
if (cache.params == params() && cache.style == style)
return cache.screen_label;
// The label has changed, so we have to re-create it.
string const before = string();
string const after = getOptions();
string const glabel = generateLabel(buffer);
unsigned int const maxLabelChars = 45;
string label = glabel;
if (label.size() > maxLabelChars) {
label.erase(maxLabelChars-3);
label += "...";
}
cache.style = style;
cache.params = params();
cache.generated_label = glabel;
cache.screen_label = label;
return label;
}
void InsetCitation::edit(BufferView * bv, int, int, unsigned int)
{
// A call to edit() indicates that we're no longer loading the
// buffer but doing some real work.
// Doesn't matter if there is no bv->buffer() entry in the map.
loading_buffer[bv->buffer()] = false;
bv->owner()->getDialogs()->showCitation(this);
}
void InsetCitation::edit(BufferView * bv, bool)
{
edit(bv, 0, 0, 0);
}
int InsetCitation::ascii(Buffer const *, ostream & os, int) const
int InsetCitation::ascii(Buffer const * buffer, ostream & os, int) const
{
os << "[" << getContents() << "]";
string label;
if (cache.params == params() && cache.style == getStyle(buffer))
label = cache.generated_label;
else
label = generateLabel(buffer);
os << label;
return 0;
}
// Have to overwrite the default InsetCommand method in order to check that
// the \cite command is valid. Eg, the user has natbib enabled, inputs some
// citations and then changes his mind, turning natbib support off. The output
@ -92,14 +342,19 @@ int InsetCitation::latex(Buffer const * buffer, ostream & os,
os << getCmdName();
else
os << "cite";
string const before = string();
string const after = getOptions();
if (!before.empty() && buffer->params.use_natbib)
os << "[" << before << "][" << after << "]";
else if (!after.empty())
os << "[" << after << "]";
if (!getOptions().empty())
os << "[" << getOptions() << "]";
string::const_iterator it = getContents().begin();
string::const_iterator end = getContents().end();
// Paranoia check: make sure that there is no whitespace in here
string content;
for (string::const_iterator it = getContents().begin();
it != getContents().end(); ++it) {
for (; it != end; ++it) {
if (*it != ' ') content += *it;
}

View File

@ -43,6 +43,36 @@ public:
int latex(Buffer const *, std::ostream &, bool, bool) const;
///
void validate(LaTeXFeatures &) const;
private:
struct Cache {
///
enum Style {
///
BASIC,
///
NATBIB_AY,
///
NATBIB_NUM
};
///
Cache() : style(BASIC) {}
///
Style style;
///
InsetCommandParams params;
///
string generated_label;
///
string screen_label;
};
/// This function does the donkey work of creating the pretty label
string const generateLabel(Buffer const *) const;
///
Cache::Style getStyle(Buffer const * buffer) const;
///
mutable Cache cache;
};
#endif // INSET_CITE_H