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().params().pdfoptions().use_hyperref;
265 if (rp.inulemcmd > 0)
268 if (buffer().params().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().params().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::xhtml(XMLStream & xs, OutputParams const & op) const
387 docstring const & ref = getParam("reference");
388 InsetLabel const * il = buffer().insetLabel(ref, true);
389 string const & cmd = params().getCmdName();
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.
402 display_string = translateIfPossible(from_ascii("elsewhere"),
403 op.local_font->language()->lang());
404 else if (cmd == "eqref")
405 display_string = '(' + value + ')';
406 else if (cmd == "formatted") {
407 display_string = il->prettyCounter();
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;
423 // FIXME What we'd really like to do is to be able to output some
424 // appropriate sort of text here. But to do that, we need to associate
425 // some sort of counter with the label, and we don't have that yet.
426 docstring const attr = "href=\"#" + xml::cleanAttr(ref) + '"';
427 xs << xml::StartTag("a", to_utf8(attr));
428 xs << display_string;
429 xs << xml::EndTag("a");
434 void InsetRef::toString(odocstream & os) const
436 odocstringstream ods;
437 plaintext(ods, OutputParams(nullptr));
442 void InsetRef::forOutliner(docstring & os, size_t const, bool const) const
444 // It's hard to know what to do here. Should we show XREF in the TOC?
445 // Or should we just show that there is one? For now, we do the former.
446 odocstringstream ods;
447 plaintext(ods, OutputParams(nullptr));
452 void InsetRef::updateBuffer(ParIterator const & it, UpdateType, bool const /*deleted*/)
454 docstring const & ref = getParam("reference");
456 // Check if this one is active (i.e., neither deleted with change-tracking
457 // nor in an inset that does not produce output, such as notes or inactive branches)
458 Paragraph const & para = it.paragraph();
459 active_ = !para.isDeleted(it.pos()) && para.inInset().producesOutput();
460 // If not, check whether we are in a deleted/non-outputting inset
462 for (size_type sl = 0 ; sl < it.depth() ; ++sl) {
463 Paragraph const & outer_par = it[sl].paragraph();
464 if (outer_par.isDeleted(it[sl].pos())
465 || !outer_par.inInset().producesOutput()) {
472 // register this inset into the buffer reference cache.
473 buffer().addReference(ref, this, it);
476 string const & cmd = getCmdName();
477 for (int i = 0; !types[i].latex_name.empty(); ++i) {
478 if (cmd == types[i].latex_name) {
479 label = _(types[i].short_gui_name);
480 // indicate no hyperlink (starred)
481 if (cmd != "formatted" && cmd != "labelonly") {
482 bool const isNoLink = getParam("nolink") == "true";
484 label += from_ascii("*");
486 // indicate plural and caps
487 if (cmd == "formatted") {
488 bool const isPlural = getParam("plural") == "true";
489 bool const isCaps = getParam("caps") == "true";
491 label += from_ascii("+");
493 // up arrow (shift key) symbol
494 label += docstring(1, char_type(0x21E7));
497 label += from_ascii(": ");
502 if (cmd != "labelonly")
505 if (getParam("noprefix") != "true")
509 docstring suffix = split(ref, prefix, ':');
510 if (suffix.empty()) {
518 if (!buffer().params().isLatex() && !getParam("name").empty()) {
520 label += getParam("name");
523 unsigned int const maxLabelChars = 24;
524 if (label.size() > maxLabelChars) {
526 support::truncateWithEllipsis(label, maxLabelChars);
528 tooltip_ = from_ascii("");
530 screen_label_ = label;
536 docstring InsetRef::screenLabel() const
538 return (broken_ ? _("BROKEN: ") : docstring()) + screen_label_;
542 void InsetRef::addToToc(DocIterator const & cpit, bool output_active,
543 UpdateType, TocBackend & backend) const
545 active_ = output_active;
546 docstring const & label = getParam("reference");
547 if (buffer().insetLabel(label)) {
548 broken_ = !buffer().activeLabel(label) && active_;
550 if (broken_ && output_active) {
551 shared_ptr<Toc> toc2 = backend.toc("brokenrefs");
552 toc2->push_back(TocItem(cpit, 0, screenLabel(), output_active));
554 // This InsetRef has already been taken care of in InsetLabel::addToToc().
558 // It seems that this reference does not point to any valid label.
561 shared_ptr<Toc> toc = backend.toc("label");
562 if (TocBackend::findItem(*toc, 0, label) == toc->end())
563 toc->push_back(TocItem(cpit, 0, label, output_active, true));
564 toc->push_back(TocItem(cpit, 1, screenLabel(), output_active));
565 shared_ptr<Toc> toc2 = backend.toc("brokenrefs");
566 toc2->push_back(TocItem(cpit, 0, screenLabel(), output_active));
570 void InsetRef::validate(LaTeXFeatures & features) const
572 string const & cmd = getCmdName();
573 if (cmd == "vref" || cmd == "vpageref")
574 features.require("varioref");
575 else if (cmd == "formatted") {
576 docstring const data = getEscapedLabel(features.runparams());
579 bool const use_refstyle = buffer().params().use_refstyle;
580 bool const use_caps = getParam("caps") == "true";
581 docstring const fcmd =
582 getFormattedCmd(data, label, prefix, use_refstyle, use_caps);
584 features.require("refstyle");
586 features.addPreambleSnippet(from_ascii("\\let\\charef=\\chapref"));
587 else if (!prefix.empty()) {
588 docstring lcmd = "\\AtBeginDocument{\\providecommand" +
589 fcmd + "[1]{\\ref{" + prefix + ":#1}}}";
590 features.addPreambleSnippet(lcmd);
593 features.require("prettyref");
594 // prettyref uses "cha" for chapters, so we provide a kind of
596 if (prefix == "chap")
597 features.addPreambleSnippet(from_ascii("\\let\\pr@chap=\\pr@cha"));
599 } else if (cmd == "eqref" && !buffer().params().use_refstyle)
600 // with refstyle, we simply output "(\ref{label})"
601 features.require("amsmath");
602 else if (cmd == "nameref")
603 features.require("nameref");
606 bool InsetRef::forceLTR(OutputParams const & rp) const
608 // We force LTR for references. However,
609 // * Namerefs are output in the scripts direction
610 // at least with fontspec/bidi and luabidi, though (see #11518).
611 // * Parentheses are automatically swapped with XeTeX/bidi
612 // [not with LuaTeX/luabidi] (see #11626).
613 // FIXME: Re-Audit all other RTL cases.
614 if (rp.useBidiPackage())
616 return (getCmdName() != "nameref" || !buffer().masterParams().useNonTeXFonts);
620 InsetRef::type_info const InsetRef::types[] = {
621 { "ref", N_("Standard"), N_("Ref")},
622 { "eqref", N_("Equation"), N_("EqRef")},
623 { "pageref", N_("Page Number"), N_("Page")},
624 { "vpageref", N_("Textual Page Number"), N_("TextPage")},
625 { "vref", N_("Standard+Textual Page"), N_("Ref+Text")},
626 { "nameref", N_("Reference to Name"), N_("NameRef")},
627 { "formatted", N_("Formatted"), N_("Format")},
628 { "labelonly", N_("Label Only"), N_("Label")},
633 docstring InsetRef::getTOCString() const
635 docstring const & label = getParam("reference");
636 if (buffer().insetLabel(label))
637 broken_ = !buffer().activeLabel(label) && active_;
640 return tooltip_.empty() ? screenLabel() : tooltip_;