3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
15 #include "BufferParams.h"
17 #include "DispatchResult.h"
18 #include "FuncStatus.h"
19 #include "InsetLabel.h"
21 #include "LaTeXFeatures.h"
23 #include "OutputParams.h"
24 #include "output_xhtml.h"
25 #include "Paragraph.h"
26 #include "ParIterator.h"
28 #include "texstream.h"
29 #include "TocBackend.h"
31 #include "support/debug.h"
32 #include "support/docstream.h"
33 #include "support/gettext.h"
34 #include "support/lstrings.h"
35 #include "support/textutils.h"
37 using namespace lyx::support;
43 InsetRef::InsetRef(Buffer * buf, InsetCommandParams const & p)
44 : InsetCommand(buf, p), broken_(false), active_(true)
48 InsetRef::InsetRef(InsetRef const & ir)
49 : InsetCommand(ir), broken_(false), active_(true)
53 bool InsetRef::isCompatibleCommand(string const & s) {
54 //FIXME This is likely not the best way to handle this.
55 //But this stuff is hardcoded elsewhere already.
61 || s == "prettyref" // for InsetMathRef FIXME
68 ParamInfo const & InsetRef::findInfo(string const & /* cmdName */)
70 static ParamInfo param_info_;
71 if (param_info_.empty()) {
72 param_info_.add("name", ParamInfo::LATEX_OPTIONAL);
73 param_info_.add("reference", ParamInfo::LATEX_REQUIRED,
74 ParamInfo::HANDLING_ESCAPE);
75 param_info_.add("plural", ParamInfo::LYX_INTERNAL);
76 param_info_.add("caps", ParamInfo::LYX_INTERNAL);
77 param_info_.add("noprefix", ParamInfo::LYX_INTERNAL);
83 docstring InsetRef::layoutName() const
85 return from_ascii("Ref");
89 void InsetRef::changeTarget(docstring const & new_label)
91 // With change tracking, we insert a new ref
92 // and delete the old one
93 if (buffer().masterParams().track_changes) {
94 InsetCommandParams icp(REF_CODE, "ref");
95 icp["reference"] = new_label;
96 string const data = InsetCommand::params2string(icp);
97 lyx::dispatch(FuncRequest(LFUN_INSET_INSERT, data));
98 lyx::dispatch(FuncRequest(LFUN_CHAR_DELETE_FORWARD));
100 setParam("reference", new_label);
105 void InsetRef::doDispatch(Cursor & cur, FuncRequest & cmd)
107 string const inset = cmd.getArg(0);
108 string const arg = cmd.getArg(1);
110 if (cmd.action() == LFUN_INSET_MODIFY && inset == "ref") {
111 if (arg == "toggle-plural")
113 else if (arg == "toggle-caps")
115 else if (arg == "toggle-noprefix")
116 pstring = "noprefix";
117 else if (arg == "changetarget") {
118 string const oldtarget = cmd.getArg(2);
119 string const newtarget = cmd.getArg(3);
120 if (!oldtarget.empty() && !newtarget.empty()
121 && getParam("reference") == from_utf8(oldtarget))
122 changeTarget(from_utf8(newtarget));
123 cur.forceBufferUpdate();
127 // otherwise not for us
129 return InsetCommand::doDispatch(cur, cmd);
131 bool const isSet = (getParam(pstring) == "true");
132 setParam(pstring, from_ascii(isSet ? "false" : "true"));
136 bool InsetRef::getStatus(Cursor & cur, FuncRequest const & cmd,
137 FuncStatus & status) const
139 if (cmd.action() != LFUN_INSET_MODIFY)
140 return InsetCommand::getStatus(cur, cmd, status);
141 if (cmd.getArg(0) != "ref")
142 return InsetCommand::getStatus(cur, cmd, status);
144 string const arg = cmd.getArg(1);
146 if (arg == "changetarget")
148 if (arg == "toggle-plural")
150 else if (arg == "toggle-caps")
152 if (!pstring.empty()) {
153 status.setEnabled(buffer().params().use_refstyle &&
154 params().getCmdName() == "formatted");
155 bool const isSet = (getParam(pstring) == "true");
156 status.setOnOff(isSet);
159 if (arg == "toggle-noprefix") {
160 status.setEnabled(params().getCmdName() == "labelonly");
161 bool const isSet = (getParam("noprefix") == "true");
162 status.setOnOff(isSet);
165 // otherwise not for us
166 return InsetCommand::getStatus(cur, cmd, status);
172 void capitalize(docstring & s) {
173 char_type t = uppercase(s[0]);
180 // the ref argument is the label name we are referencing.
181 // we expect ref to be in the form: pfx:suffix.
183 // if it isn't, then we can't produce a formatted reference,
184 // so we return "\ref" and put ref into label.
186 // for refstyle, we return "\pfxcmd", and put suffix into
187 // label and pfx into prefix. this is because refstyle expects
188 // the command: \pfxcmd{suffix}.
190 // for prettyref, we return "\prettyref" and put ref into label
191 // and pfx into prefix. this is because prettyref uses the whole
192 // label, thus: \prettyref{pfx:suffix}.
194 docstring InsetRef::getFormattedCmd(docstring const & ref,
195 docstring & label, docstring & prefix, docstring const & caps) const
197 static docstring const defcmd = from_ascii("\\ref");
198 static docstring const prtcmd = from_ascii("\\prettyref");
200 label = split(ref, prefix, ':');
202 // we have to have xxx:xxxxx...
204 LYXERR0("Label `" << ref << "' contains no `:' separator.");
206 prefix = from_ascii("");
210 if (prefix.empty()) {
216 if (!buffer().params().use_refstyle) {
217 // \prettyref uses the whole label
222 // make sure the prefix is legal for a latex command
223 int const len = prefix.size();
224 for (int i = 0; i < len; i++) {
225 char_type const c = prefix[i];
226 if (!isAlphaASCII(c)) {
227 LYXERR0("Prefix `" << prefix << "' is invalid for LaTeX.");
233 if (caps == "true") {
236 return from_ascii("\\") + prefix + from_ascii("ref");
240 docstring InsetRef::getEscapedLabel(OutputParams const & rp) const
242 InsetCommandParams const & p = params();
243 ParamInfo const & pi = p.info();
244 ParamInfo::ParamData const & pd = pi["reference"];
245 return p.prepareCommand(rp, getParam("reference"), pd.handling());
249 void InsetRef::latex(otexstream & os, OutputParams const & rp) const
251 string const & cmd = getCmdName();
252 docstring const & data = getEscapedLabel(rp);
254 if (rp.inulemcmd > 0)
257 if (cmd == "eqref" && buffer().params().use_refstyle) {
258 // we advertise this as printing "(n)", so we'll do that, at least
259 // for refstyle, since refstlye's own \eqref prints, by default,
260 // "equation n". if one wants \eqref, one can get it by using a
261 // formatted label in this case.
262 os << '(' << from_ascii("\\ref{") << data << from_ascii("})");
264 else if (cmd == "formatted") {
267 docstring const fcmd =
268 getFormattedCmd(data, label, prefix, getParam("caps"));
270 if (buffer().params().use_refstyle && getParam("plural") == "true")
272 os << '{' << label << '}';
274 else if (cmd == "labelonly") {
275 docstring const & ref = getParam("reference");
276 if (getParam("noprefix") != "true")
280 docstring suffix = split(ref, prefix, ':');
281 if (suffix.empty()) {
282 LYXERR0("Label `" << ref << "' contains no `:' separator.");
290 // We don't want to output p_["name"], since that is only used
291 // in docbook. So we construct new params, without it, and use that.
292 InsetCommandParams p(REF_CODE, cmd);
293 docstring const ref = getParam("reference");
294 p["reference"] = ref;
295 os << p.getCommand(rp);
298 if (rp.inulemcmd > 0)
303 int InsetRef::plaintext(odocstringstream & os,
304 OutputParams const &, size_t) const
306 docstring const str = getParam("reference");
307 os << '[' << str << ']';
308 return 2 + str.size();
312 int InsetRef::docbook(odocstream & os, OutputParams const & runparams) const
314 docstring const & name = getParam("name");
316 if (runparams.flavor == OutputParams::XML) {
317 os << "<xref linkend=\""
318 << sgml::cleanID(buffer(), runparams, getParam("reference"))
321 os << "<xref linkend=\""
322 << sgml::cleanID(buffer(), runparams, getParam("reference"))
326 os << "<link linkend=\""
327 << sgml::cleanID(buffer(), runparams, getParam("reference"))
337 docstring InsetRef::xhtml(XHTMLStream & xs, OutputParams const & op) const
339 docstring const & ref = getParam("reference");
340 InsetLabel const * il = buffer().insetLabel(ref, true);
341 string const & cmd = params().getCmdName();
342 docstring display_string;
344 if (il && !il->counterValue().empty()) {
345 // Try to construct a label from the InsetLabel we reference.
346 docstring const & value = il->counterValue();
348 display_string = value;
349 else if (cmd == "vref")
350 // normally, would be "ref on page #", but we have no pages
351 display_string = value;
352 else if (cmd == "pageref" || cmd == "vpageref")
353 // normally would be "on page #", but we have no pages.
354 display_string = translateIfPossible(from_ascii("elsewhere"),
355 op.local_font->language()->lang());
356 else if (cmd == "eqref")
357 display_string = '(' + value + ')';
358 else if (cmd == "formatted") {
359 display_string = il->prettyCounter();
360 if (buffer().params().use_refstyle && getParam("caps") == "true")
361 capitalize(display_string);
362 // it is hard to see what to do about plurals...
364 else if (cmd == "nameref")
365 // FIXME We don't really have the ability to handle these
366 // properly in XHTML output yet (bug #8599).
367 // It might not be that hard to do. We have the InsetLabel,
368 // and we can presumably find its paragraph using the TOC.
369 // But the label might be referencing a section, yet not be
370 // in that section. So this is not trivial.
371 display_string = il->prettyCounter();
373 display_string = ref;
375 // FIXME What we'd really like to do is to be able to output some
376 // appropriate sort of text here. But to do that, we need to associate
377 // some sort of counter with the label, and we don't have that yet.
378 docstring const attr = "href=\"#" + html::cleanAttr(ref) + '"';
379 xs << html::StartTag("a", to_utf8(attr));
380 xs << display_string;
381 xs << html::EndTag("a");
386 void InsetRef::toString(odocstream & os) const
388 odocstringstream ods;
389 plaintext(ods, OutputParams(0));
394 void InsetRef::forOutliner(docstring & os, size_t const, bool const) const
396 // There's no need for details in the TOC, and a long label
397 // will just get in the way.
402 void InsetRef::updateBuffer(ParIterator const & it, UpdateType, bool const /*deleted*/)
404 docstring const & ref = getParam("reference");
406 // Check if this one is active (i.e., neither deleted with change-tracking
407 // nor in an inset that does not produce output, such as notes or inactive branches)
408 Paragraph const & para = it.paragraph();
409 active_ = !para.isDeleted(it.pos()) && para.inInset().producesOutput();
410 // If not, check whether we are in a deleted/non-outputting inset
412 for (size_type sl = 0 ; sl < it.depth() ; ++sl) {
413 Paragraph const & outer_par = it[sl].paragraph();
414 if (outer_par.isDeleted(it[sl].pos())
415 || !outer_par.inInset().producesOutput()) {
422 // register this inset into the buffer reference cache.
423 buffer().addReference(ref, this, it);
426 string const & cmd = getCmdName();
427 for (int i = 0; !types[i].latex_name.empty(); ++i) {
428 if (cmd == types[i].latex_name) {
429 label = _(types[i].short_gui_name);
434 if (cmd != "labelonly")
437 if (getParam("noprefix") != "true")
441 docstring suffix = split(ref, prefix, ':');
442 if (suffix.empty()) {
450 if (!buffer().params().isLatex() && !getParam("name").empty()) {
452 label += getParam("name");
455 unsigned int const maxLabelChars = 24;
456 if (label.size() > maxLabelChars) {
458 support::truncateWithEllipsis(label, maxLabelChars);
460 tooltip_ = from_ascii("");
462 screen_label_ = label;
468 docstring InsetRef::screenLabel() const
470 return (broken_ ? _("BROKEN: ") : docstring()) + screen_label_;
474 void InsetRef::addToToc(DocIterator const & cpit, bool output_active,
475 UpdateType, TocBackend & backend) const
477 active_ = output_active;
478 docstring const & label = getParam("reference");
479 if (buffer().insetLabel(label)) {
480 broken_ = !buffer().activeLabel(label);
482 if (broken_ && output_active) {
483 shared_ptr<Toc> toc2 = backend.toc("brokenrefs");
484 toc2->push_back(TocItem(cpit, 0, screenLabel(), output_active));
486 // This InsetRef has already been taken care of in InsetLabel::addToToc().
490 // It seems that this reference does not point to any valid label.
493 shared_ptr<Toc> toc = backend.toc("label");
494 toc->push_back(TocItem(cpit, 0, screenLabel(), output_active));
495 shared_ptr<Toc> toc2 = backend.toc("brokenrefs");
496 toc2->push_back(TocItem(cpit, 0, screenLabel(), output_active));
500 void InsetRef::validate(LaTeXFeatures & features) const
502 string const cmd = getCmdName();
503 if (cmd == "vref" || cmd == "vpageref")
504 features.require("varioref");
505 else if (cmd == "formatted") {
506 docstring const data = getEscapedLabel(features.runparams());
509 docstring const fcmd =
510 getFormattedCmd(data, label, prefix, getParam("caps"));
511 if (buffer().params().use_refstyle) {
512 features.require("refstyle");
514 features.addPreambleSnippet(from_ascii("\\let\\charef=\\chapref"));
515 else if (!prefix.empty()) {
516 docstring lcmd = "\\AtBeginDocument{\\providecommand" +
517 fcmd + "[1]{\\ref{" + prefix + ":#1}}}";
518 features.addPreambleSnippet(lcmd);
521 features.require("prettyref");
522 // prettyref uses "cha" for chapters, so we provide a kind of
524 if (prefix == "chap")
525 features.addPreambleSnippet(from_ascii("\\let\\pr@chap=\\pr@cha"));
527 } else if (cmd == "eqref" && !buffer().params().use_refstyle)
528 // with refstyle, we simply output "(\ref{label})"
529 features.require("amsmath");
530 else if (cmd == "nameref")
531 features.require("nameref");
534 bool InsetRef::forceLTR(OutputParams const & rp) const
536 // We force LTR for references. However,
537 // * Namerefs are output in the scripts direction
538 // at least with fontspec/bidi and luabidi, though (see #11518).
539 // * Parentheses are automatically swapped with XeTeX/bidi
540 // [not with LuaTeX/luabidi] (see #11626).
541 // FIXME: Re-Audit all other RTL cases.
542 if (rp.useBidiPackage())
544 return (getCmdName() != "nameref" || !buffer().masterParams().useNonTeXFonts);
548 InsetRef::type_info const InsetRef::types[] = {
549 { "ref", N_("Standard"), N_("Ref: ")},
550 { "eqref", N_("Equation"), N_("EqRef: ")},
551 { "pageref", N_("Page Number"), N_("Page: ")},
552 { "vpageref", N_("Textual Page Number"), N_("TextPage: ")},
553 { "vref", N_("Standard+Textual Page"), N_("Ref+Text: ")},
554 { "nameref", N_("Reference to Name"), N_("NameRef: ")},
555 { "formatted", N_("Formatted"), N_("Format: ")},
556 { "labelonly", N_("Label Only"), N_("Label: ")},
561 docstring InsetRef::getTOCString() const
563 docstring const & label = getParam("reference");
564 if (buffer().insetLabel(label))
565 broken_ = !buffer().activeLabel(label) && active_;
568 return tooltip_.empty() ? screenLabel() : tooltip_;