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 "output_xhtml.h"
24 #include "Paragraph.h"
25 #include "ParIterator.h"
26 #include "PDFOptions.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);
78 param_info_.add("nolink", ParamInfo::LYX_INTERNAL);
84 docstring InsetRef::layoutName() const
86 return from_ascii("Ref");
90 void InsetRef::changeTarget(docstring const & new_label)
92 // With change tracking, we insert a new ref
93 // and delete the old one
94 if (buffer().masterParams().track_changes) {
95 InsetCommandParams icp(REF_CODE, "ref");
96 icp["reference"] = new_label;
97 string const data = InsetCommand::params2string(icp);
98 lyx::dispatch(FuncRequest(LFUN_INSET_INSERT, data));
99 lyx::dispatch(FuncRequest(LFUN_CHAR_DELETE_FORWARD));
101 setParam("reference", new_label);
106 void InsetRef::doDispatch(Cursor & cur, FuncRequest & cmd)
108 // Ctrl + click: go to label
109 if (cmd.action() == LFUN_MOUSE_RELEASE && cmd.modifier() == ControlModifier) {
110 lyx::dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
111 lyx::dispatch(FuncRequest(LFUN_LABEL_GOTO, getParam("reference")));
115 string const inset = cmd.getArg(0);
116 string const arg = cmd.getArg(1);
118 if (cmd.action() == LFUN_INSET_MODIFY && inset == "ref") {
119 if (arg == "toggle-plural")
121 else if (arg == "toggle-caps")
123 else if (arg == "toggle-noprefix")
124 pstring = "noprefix";
125 else if (arg == "toggle-nolink")
127 else if (arg == "changetarget") {
128 string const oldtarget = cmd.getArg(2);
129 string const newtarget = cmd.getArg(3);
130 if (!oldtarget.empty() && !newtarget.empty()
131 && getParam("reference") == from_utf8(oldtarget))
132 changeTarget(from_utf8(newtarget));
133 cur.forceBufferUpdate();
138 // otherwise not for us
140 return InsetCommand::doDispatch(cur, cmd);
142 bool const isSet = (getParam(pstring) == "true");
143 setParam(pstring, from_ascii(isSet ? "false" : "true"));
144 cur.forceBufferUpdate();
148 bool InsetRef::getStatus(Cursor & cur, FuncRequest const & cmd,
149 FuncStatus & status) const
151 if (cmd.action() != LFUN_INSET_MODIFY)
152 return InsetCommand::getStatus(cur, cmd, status);
153 if (cmd.getArg(0) != "ref")
154 return InsetCommand::getStatus(cur, cmd, status);
156 string const arg = cmd.getArg(1);
158 if (arg == "changetarget")
160 if (arg == "toggle-plural")
162 else if (arg == "toggle-caps")
164 if (!pstring.empty()) {
165 status.setEnabled(buffer().params().use_refstyle &&
166 params().getCmdName() == "formatted");
167 bool const isSet = (getParam(pstring) == "true");
168 status.setOnOff(isSet);
171 if (arg == "toggle-noprefix") {
172 status.setEnabled(params().getCmdName() == "labelonly");
173 bool const isSet = (getParam("noprefix") == "true");
174 status.setOnOff(isSet);
177 if (arg == "toggle-nolink") {
178 status.setEnabled(params().getCmdName() != "formatted" && params().getCmdName() != "labelonly");
179 bool const isSet = (getParam("nolink") == "true");
180 status.setOnOff(isSet);
183 // otherwise not for us
184 return InsetCommand::getStatus(cur, cmd, status);
188 // the ref argument is the label name we are referencing.
189 // we expect ref to be in the form: pfx:suffix.
191 // if it isn't, then we can't produce a formatted reference,
192 // so we return "\ref" and put ref into label.
194 // for refstyle, we return "\pfxcmd", and put suffix into
195 // label and pfx into prefix. this is because refstyle expects
196 // the command: \pfxcmd{suffix}.
198 // for prettyref, we return "\prettyref" and put ref into label
199 // and pfx into prefix. this is because prettyref uses the whole
200 // label, thus: \prettyref{pfx:suffix}.
202 docstring InsetRef::getFormattedCmd(docstring const & ref,
203 docstring & label, docstring & prefix, bool use_refstyle,
206 static docstring const defcmd = from_ascii("\\ref");
207 static docstring const prtcmd = from_ascii("\\prettyref");
209 label = split(ref, prefix, ':');
211 // we have to have xxx:xxxxx...
213 LYXERR0("Label `" << ref << "' contains no `:' separator.");
215 prefix = from_ascii("");
219 if (prefix.empty()) {
221 LYXERR0("Label `" << ref << "' contains nothign before `:'.");
227 // \prettyref uses the whole label
232 // make sure the prefix is legal for a latex command
233 size_t const len = prefix.size();
234 for (size_t i = 0; i < len; i++) {
235 char_type const c = prefix[i];
236 if (!isAlphaASCII(c)) {
237 LYXERR0("Prefix `" << prefix << "' is invalid for LaTeX.");
244 prefix = support::capitalize(prefix);
246 return from_ascii("\\") + prefix + from_ascii("ref");
250 docstring InsetRef::getEscapedLabel(OutputParams const & rp) const
252 InsetCommandParams const & p = params();
253 ParamInfo const & pi = p.info();
254 ParamInfo::ParamData const & pd = pi["reference"];
255 return p.prepareCommand(rp, getParam("reference"), pd.handling());
259 void InsetRef::latex(otexstream & os, OutputParams const & rp) const
261 string const & cmd = getCmdName();
262 docstring const & data = getEscapedLabel(rp);
263 bool const hyper_on = buffer().masterParams().pdfoptions().use_hyperref;
265 if (rp.inulemcmd > 0)
268 if (buffer().masterParams().use_refstyle && cmd == "eqref") {
269 // we advertise this as printing "(n)", so we'll do that, at least
270 // for refstyle, since refstlye's own \eqref prints, by default,
271 // "equation n". if one wants \eqref, one can get it by using a
272 // formatted label in this case.
273 bool const use_nolink = hyper_on && getParam("nolink") == "true";
274 os << '(' << from_ascii("\\ref") +
275 // no hyperlink version?
276 (use_nolink ? from_utf8("*") : from_utf8("")) +
277 from_ascii("{") << data << from_ascii("})");
279 else if (cmd == "formatted") {
282 bool const use_caps = getParam("caps") == "true";
283 bool const use_plural = getParam("plural") == "true";
284 bool const use_refstyle = buffer().masterParams().use_refstyle;
285 docstring const fcmd =
286 getFormattedCmd(data, label, prefix, use_refstyle, use_caps);
288 if (use_refstyle && use_plural)
290 os << '{' << label << '}';
292 else if (cmd == "labelonly") {
293 docstring const & ref = getParam("reference");
294 if (getParam("noprefix") != "true")
298 docstring suffix = split(ref, prefix, ':');
299 if (suffix.empty()) {
300 LYXERR0("Label `" << ref << "' contains no `:' separator.");
308 InsetCommandParams p(REF_CODE, cmd);
309 bool const use_nolink = hyper_on && getParam("nolink") == "true";
310 docstring const ref = getParam("reference");
311 p["reference"] = ref;
312 os << p.getCommand(rp, use_nolink);
315 if (rp.inulemcmd > 0)
320 int InsetRef::plaintext(odocstringstream & os,
321 OutputParams const &, size_t) const
323 docstring const str = getParam("reference");
324 os << '[' << str << ']';
325 return 2 + int(str.size());
329 void InsetRef::docbook(XMLStream & xs, OutputParams const &) const
331 docstring const & ref = getParam("reference");
332 InsetLabel const * il = buffer().insetLabel(ref, true);
333 string const & cmd = params().getCmdName();
334 docstring linkend = xml::cleanID(ref);
336 // A name is provided, LyX will provide it. This is supposed to be a very rare case.
337 // Link with linkend, as is it within the document (not outside, in which case xlink:href is better suited).
338 docstring const & name = getParam("name");
340 docstring attr = from_utf8("linkend=\"") + linkend + from_utf8("\"");
342 xs << xml::StartTag("link", to_utf8(attr));
344 xs << xml::EndTag("link");
348 // The DocBook processor will generate the name when required.
349 docstring display_before;
350 docstring display_after;
353 if (il && !il->counterValue().empty()) {
354 // Try to construct a label from the InsetLabel we reference.
355 if (cmd == "vref" || cmd == "pageref" || cmd == "vpageref" || cmd == "nameref" || cmd == "formatted") {
356 // "ref on page #", "on page #", etc. The DocBook processor deals with generating the right text,
357 // including in the right language.
358 role = from_ascii(cmd);
360 if (cmd == "formatted") {
361 // A formatted reference may have many parameters. Generate all of them as roles, the only
362 // way arbitrary parameters can be passed into DocBook.
363 if (buffer().params().use_refstyle && getParam("caps") == "true")
364 role += " refstyle-caps";
365 if (buffer().params().use_refstyle && getParam("plural") == "true")
366 role += " refstyle-plural";
368 } else if (cmd == "eqref") {
369 display_before = from_ascii("(");
370 display_after = from_ascii(")");
372 // TODO: what about labelonly? I don't get how this is supposed to work...
375 // No name, ask DocBook to generate one.
376 docstring attr = from_utf8("linkend=\"") + xml::cleanID(ref) + from_utf8("\"");
378 attr += " role=\"" + role + "\"";
379 xs << display_before;
380 xs << xml::CompTag("xref", to_utf8(attr));
385 docstring InsetRef::displayString(docstring const & ref, string const & cmd,
386 string const & language) const
389 InsetLabel const * il = buffer().insetLabel(ref, true);
390 docstring display_string;
392 if (il && !il->counterValue().empty()) {
393 // Try to construct a label from the InsetLabel we reference.
394 docstring const & value = il->counterValue();
396 display_string = value;
397 else if (cmd == "vref")
398 // normally, would be "ref on page #", but we have no pages
399 display_string = value;
400 else if (cmd == "pageref" || cmd == "vpageref") {
401 // normally would be "on page #", but we have no pages.
403 translateIfPossible(from_ascii("elsewhere"), language);
404 } else if (cmd == "eqref")
405 display_string = '(' + value + ')';
406 else if (cmd == "formatted") {
407 display_string = il->formattedCounter();
408 if (buffer().params().use_refstyle && getParam("caps") == "true")
409 capitalize(display_string);
410 // it is hard to see what to do about plurals...
412 else if (cmd == "nameref")
413 // FIXME We don't really have the ability to handle these
414 // properly in XHTML output yet (bug #8599).
415 // It might not be that hard to do. We have the InsetLabel,
416 // and we can presumably find its paragraph using the TOC.
417 // But the label might be referencing a section, yet not be
418 // in that section. So this is not trivial.
419 display_string = il->prettyCounter();
421 display_string = ref;
422 return display_string;
426 docstring InsetRef::xhtml(XMLStream & xs, OutputParams const & op) const
428 docstring const & ref = getParam("reference");
429 string const & cmd = params().getCmdName();
430 // FIXME What we'd really like to do is to be able to output some
431 // appropriate sort of text here. But to do that, we need to associate
432 // some sort of counter with the label, and we don't have that yet.
433 docstring const attr = "href=\"#" + xml::cleanAttr(ref) + '"';
434 xs << xml::StartTag("a", to_utf8(attr));
435 xs << displayString(ref, cmd, getLocalOrDefaultLang(op)->lang());
436 xs << xml::EndTag("a");
441 void InsetRef::toString(odocstream & os) const
443 odocstringstream ods;
444 plaintext(ods, OutputParams(nullptr));
449 void InsetRef::forOutliner(docstring & os, size_t const, bool const) const
451 // It's hard to know what to do here. Should we show XREF in the TOC?
452 // Or should we just show that there is one? For now, we do the former.
453 odocstringstream ods;
454 plaintext(ods, OutputParams(nullptr));
459 void InsetRef::updateBuffer(ParIterator const & it, UpdateType, bool const /*deleted*/)
461 docstring const & ref = getParam("reference");
463 // Check if this one is active (i.e., neither deleted with change-tracking
464 // nor in an inset that does not produce output, such as notes or inactive branches)
465 Paragraph const & para = it.paragraph();
466 active_ = !para.isDeleted(it.pos()) && para.inInset().producesOutput();
467 // If not, check whether we are in a deleted/non-outputting inset
469 for (size_type sl = 0 ; sl < it.depth() ; ++sl) {
470 Paragraph const & outer_par = it[sl].paragraph();
471 if (outer_par.isDeleted(it[sl].pos())
472 || !outer_par.inInset().producesOutput()) {
479 // register this inset into the buffer reference cache.
480 buffer().addReference(ref, this, it);
483 string const & cmd = getCmdName();
484 for (int i = 0; !types[i].latex_name.empty(); ++i) {
485 if (cmd == types[i].latex_name) {
486 label = _(types[i].short_gui_name);
487 // indicate no hyperlink (starred)
488 if (cmd != "formatted" && cmd != "labelonly") {
489 bool const isNoLink = getParam("nolink") == "true";
491 label += from_ascii("*");
493 // indicate plural and caps
494 if (cmd == "formatted") {
495 bool const isPlural = getParam("plural") == "true";
496 bool const isCaps = getParam("caps") == "true";
498 // up arrow (shift key) symbol
499 label += docstring(1, char_type(0x21E7));
502 label += from_ascii("+");
504 label += from_ascii(": ");
509 if (cmd != "labelonly")
512 if (getParam("noprefix") != "true")
516 docstring suffix = split(ref, prefix, ':');
517 if (suffix.empty()) {
525 if (!buffer().params().isLatex() && !getParam("name").empty()) {
527 label += getParam("name");
530 bool const use_formatted_ref = buffer().params().use_formatted_ref;
531 unsigned int const maxLabelChars = 24;
532 // Show label in tooltip when formatted references are shown in the work
533 // area or it is too long
534 if (use_formatted_ref || label.size() > maxLabelChars) {
536 support::truncateWithEllipsis(label, maxLabelChars);
538 // put cross-reference value into tooltip
539 tooltip_ = displayString(ref, cmd);
542 screen_label_ = label;
543 // If use_formatted_ref is active, this will be overwritten in addToToc.
544 // (We can't do it now because it might be a forward-reference
545 // and so the reference might not be in the label cache yet.
551 docstring InsetRef::screenLabel() const
553 return (broken_ ? _("BROKEN: ") : docstring()) + screen_label_;
557 void InsetRef::addToToc(DocIterator const & cpit, bool output_active,
558 UpdateType, TocBackend & backend) const
560 active_ = output_active;
561 docstring const & label = getParam("reference");
562 if (buffer().insetLabel(label)) {
563 broken_ = !buffer().activeLabel(label) && active_;
565 if (broken_ && output_active) {
566 shared_ptr<Toc> toc2 = backend.toc("brokenrefs");
567 toc2->push_back(TocItem(cpit, 0, screenLabel(), output_active));
570 // Code for display of formatted references
571 bool const use_formatted_ref = buffer().params().use_formatted_ref;
572 if (use_formatted_ref) {
573 string const & cmd = getCmdName();
574 docstring const & ref = getParam("reference");
575 if (cmd != "pageref" && cmd != "vpageref" && cmd != "vref" &&
577 screen_label_ = displayString(ref, cmd);
581 // It seems that this reference does not point to any valid label.
584 shared_ptr<Toc> toc = backend.toc("label");
585 if (TocBackend::findItem(*toc, 0, label) == toc->end())
586 toc->push_back(TocItem(cpit, 0, label, output_active, true));
587 toc->push_back(TocItem(cpit, 1, screenLabel(), output_active));
588 shared_ptr<Toc> toc2 = backend.toc("brokenrefs");
589 toc2->push_back(TocItem(cpit, 0, screenLabel(), output_active));
593 void InsetRef::validate(LaTeXFeatures & features) const
595 string const & cmd = getCmdName();
596 if (cmd == "vref" || cmd == "vpageref")
597 features.require("varioref");
598 else if (cmd == "formatted") {
599 docstring const data = getEscapedLabel(features.runparams());
602 bool const use_refstyle = buffer().masterParams().use_refstyle;
603 bool const use_caps = getParam("caps") == "true";
604 docstring const fcmd =
605 getFormattedCmd(data, label, prefix, use_refstyle, use_caps);
607 features.require("refstyle");
609 features.addPreambleSnippet(from_ascii("\\let\\charef=\\chapref"));
610 else if (!prefix.empty()) {
611 docstring lcmd = "\\AtBeginDocument{\\providecommand" +
612 fcmd + "[1]{\\ref{" + prefix + ":#1}}}";
613 features.addPreambleSnippet(lcmd);
616 features.require("prettyref");
617 // prettyref uses "cha" for chapters, so we provide a kind of
619 if (prefix == "chap")
620 features.addPreambleSnippet(from_ascii("\\let\\pr@chap=\\pr@cha"));
622 } else if (cmd == "eqref" && !buffer().params().use_refstyle)
623 // with refstyle, we simply output "(\ref{label})"
624 features.require("amsmath");
625 else if (cmd == "nameref")
626 features.require("nameref");
629 bool InsetRef::forceLTR(OutputParams const & rp) const
631 // We force LTR for references. However,
632 // * Namerefs are output in the scripts direction
633 // at least with fontspec/bidi and luabidi, though (see #11518).
634 // * Parentheses are automatically swapped with XeTeX/bidi
635 // [not with LuaTeX/luabidi] (see #11626).
636 // FIXME: Re-Audit all other RTL cases.
637 if (buffer().masterParams().useBidiPackage(rp))
639 return (getCmdName() != "nameref" || !buffer().masterParams().useNonTeXFonts);
643 InsetRef::type_info const InsetRef::types[] = {
644 { "ref", N_("Standard"), N_("Ref")},
645 { "eqref", N_("Equation"), N_("EqRef")},
646 { "pageref", N_("Page Number"), N_("Page")},
647 { "vpageref", N_("Textual Page Number"), N_("TextPage")},
648 { "vref", N_("Standard+Textual Page"), N_("Ref+Text")},
649 { "nameref", N_("Reference to Name"), N_("NameRef")},
650 { "formatted", N_("Formatted"), N_("Format")},
651 { "labelonly", N_("Label Only"), N_("Label")},
656 docstring InsetRef::getTOCString() const
658 docstring const & label = getParam("reference");
659 if (buffer().insetLabel(label))
660 broken_ = !buffer().activeLabel(label) && active_;
663 return tooltip_.empty() ? screenLabel() : tooltip_;