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"
27 #include "texstream.h"
28 #include "TocBackend.h"
30 #include "support/debug.h"
31 #include "support/docstream.h"
32 #include "support/gettext.h"
33 #include "support/lstrings.h"
34 #include "support/textutils.h"
36 using namespace lyx::support;
42 InsetRef::InsetRef(Buffer * buf, InsetCommandParams const & p)
43 : InsetCommand(buf, p), broken_(false), active_(true)
47 InsetRef::InsetRef(InsetRef const & ir)
48 : InsetCommand(ir), broken_(false), active_(true)
52 bool InsetRef::isCompatibleCommand(string const & s) {
53 //FIXME This is likely not the best way to handle this.
54 //But this stuff is hardcoded elsewhere already.
60 || s == "prettyref" // for InsetMathRef FIXME
67 ParamInfo const & InsetRef::findInfo(string const & /* cmdName */)
69 static ParamInfo param_info_;
70 if (param_info_.empty()) {
71 param_info_.add("name", ParamInfo::LATEX_OPTIONAL);
72 param_info_.add("reference", ParamInfo::LATEX_REQUIRED,
73 ParamInfo::HANDLING_ESCAPE);
74 param_info_.add("plural", ParamInfo::LYX_INTERNAL);
75 param_info_.add("caps", ParamInfo::LYX_INTERNAL);
76 param_info_.add("noprefix", ParamInfo::LYX_INTERNAL);
82 docstring InsetRef::layoutName() const
84 return from_ascii("Ref");
88 void InsetRef::changeTarget(docstring const & new_label)
90 // With change tracking, we insert a new ref
91 // and delete the old one
92 if (buffer().masterParams().track_changes) {
93 InsetCommandParams icp(REF_CODE, "ref");
94 icp["reference"] = new_label;
95 string const data = InsetCommand::params2string(icp);
96 lyx::dispatch(FuncRequest(LFUN_INSET_INSERT, data));
97 lyx::dispatch(FuncRequest(LFUN_CHAR_DELETE_FORWARD));
99 setParam("reference", new_label);
104 void InsetRef::doDispatch(Cursor & cur, FuncRequest & cmd)
106 string const inset = cmd.getArg(0);
107 string const arg = cmd.getArg(1);
109 if (cmd.action() == LFUN_INSET_MODIFY && inset == "ref") {
110 if (arg == "toggle-plural")
112 else if (arg == "toggle-caps")
114 else if (arg == "toggle-noprefix")
115 pstring = "noprefix";
116 else if (arg == "changetarget") {
117 string const oldtarget = cmd.getArg(2);
118 string const newtarget = cmd.getArg(3);
119 if (!oldtarget.empty() && !newtarget.empty()
120 && getParam("reference") == from_utf8(oldtarget))
121 changeTarget(from_utf8(newtarget));
122 cur.forceBufferUpdate();
127 // Ctrl + click: go to label
128 if (cmd.action() == LFUN_MOUSE_RELEASE && cmd.modifier() == ControlModifier) {
129 lyx::dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
130 lyx::dispatch(FuncRequest(LFUN_LABEL_GOTO, getParam("reference")));
134 // otherwise not for us
136 return InsetCommand::doDispatch(cur, cmd);
138 bool const isSet = (getParam(pstring) == "true");
139 setParam(pstring, from_ascii(isSet ? "false" : "true"));
143 bool InsetRef::getStatus(Cursor & cur, FuncRequest const & cmd,
144 FuncStatus & status) const
146 if (cmd.action() != LFUN_INSET_MODIFY)
147 return InsetCommand::getStatus(cur, cmd, status);
148 if (cmd.getArg(0) != "ref")
149 return InsetCommand::getStatus(cur, cmd, status);
151 string const arg = cmd.getArg(1);
153 if (arg == "changetarget")
155 if (arg == "toggle-plural")
157 else if (arg == "toggle-caps")
159 if (!pstring.empty()) {
160 status.setEnabled(buffer().params().use_refstyle &&
161 params().getCmdName() == "formatted");
162 bool const isSet = (getParam(pstring) == "true");
163 status.setOnOff(isSet);
166 if (arg == "toggle-noprefix") {
167 status.setEnabled(params().getCmdName() == "labelonly");
168 bool const isSet = (getParam("noprefix") == "true");
169 status.setOnOff(isSet);
172 // otherwise not for us
173 return InsetCommand::getStatus(cur, cmd, status);
177 // the ref argument is the label name we are referencing.
178 // we expect ref to be in the form: pfx:suffix.
180 // if it isn't, then we can't produce a formatted reference,
181 // so we return "\ref" and put ref into label.
183 // for refstyle, we return "\pfxcmd", and put suffix into
184 // label and pfx into prefix. this is because refstyle expects
185 // the command: \pfxcmd{suffix}.
187 // for prettyref, we return "\prettyref" and put ref into label
188 // and pfx into prefix. this is because prettyref uses the whole
189 // label, thus: \prettyref{pfx:suffix}.
191 docstring InsetRef::getFormattedCmd(docstring const & ref,
192 docstring & label, docstring & prefix, bool use_refstyle,
195 static docstring const defcmd = from_ascii("\\ref");
196 static docstring const prtcmd = from_ascii("\\prettyref");
198 label = split(ref, prefix, ':');
200 // we have to have xxx:xxxxx...
202 LYXERR0("Label `" << ref << "' contains no `:' separator.");
204 prefix = from_ascii("");
208 if (prefix.empty()) {
210 LYXERR0("Label `" << ref << "' contains nothign before `:'.");
216 // \prettyref uses the whole label
221 // make sure the prefix is legal for a latex command
222 size_t const len = prefix.size();
223 for (size_t i = 0; i < len; i++) {
224 char_type const c = prefix[i];
225 if (!isAlphaASCII(c)) {
226 LYXERR0("Prefix `" << prefix << "' is invalid for LaTeX.");
233 prefix = support::capitalize(prefix);
235 return from_ascii("\\") + prefix + from_ascii("ref");
239 docstring InsetRef::getEscapedLabel(OutputParams const & rp) const
241 InsetCommandParams const & p = params();
242 ParamInfo const & pi = p.info();
243 ParamInfo::ParamData const & pd = pi["reference"];
244 return p.prepareCommand(rp, getParam("reference"), pd.handling());
248 void InsetRef::latex(otexstream & os, OutputParams const & rp) const
250 string const & cmd = getCmdName();
251 docstring const & data = getEscapedLabel(rp);
253 if (rp.inulemcmd > 0)
256 if (buffer().params().use_refstyle && cmd == "eqref") {
257 // we advertise this as printing "(n)", so we'll do that, at least
258 // for refstyle, since refstlye's own \eqref prints, by default,
259 // "equation n". if one wants \eqref, one can get it by using a
260 // formatted label in this case.
261 os << '(' << from_ascii("\\ref{") << data << from_ascii("})");
263 else if (cmd == "formatted") {
266 bool const use_caps = getParam("caps") == "true";
267 bool const use_plural = getParam("plural") == "true";
268 bool const use_refstyle = buffer().params().use_refstyle;
269 docstring const fcmd =
270 getFormattedCmd(data, label, prefix, use_refstyle, use_caps);
272 if (use_refstyle && use_plural)
274 os << '{' << label << '}';
276 else if (cmd == "labelonly") {
277 docstring const & ref = getParam("reference");
278 if (getParam("noprefix") != "true")
282 docstring suffix = split(ref, prefix, ':');
283 if (suffix.empty()) {
284 LYXERR0("Label `" << ref << "' contains no `:' separator.");
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 + int(str.size());
312 void InsetRef::docbook(XMLStream & xs, OutputParams const &) const
314 docstring const & ref = getParam("reference");
315 InsetLabel const * il = buffer().insetLabel(ref, true);
316 string const & cmd = params().getCmdName();
317 docstring linkend = xml::cleanID(ref);
319 // A name is provided, LyX will provide it. This is supposed to be a very rare case.
320 // Link with linkend, as is it within the document (not outside, in which case xlink:href is better suited).
321 docstring const & name = getParam("name");
323 docstring attr = from_utf8("linkend=\"") + linkend + from_utf8("\"");
325 xs << xml::StartTag("link", to_utf8(attr));
327 xs << xml::EndTag("link");
331 // The DocBook processor will generate the name when required.
332 docstring display_before;
333 docstring display_after;
336 if (il && !il->counterValue().empty()) {
337 // Try to construct a label from the InsetLabel we reference.
338 if (cmd == "vref" || cmd == "pageref" || cmd == "vpageref" || cmd == "nameref" || cmd == "formatted") {
339 // "ref on page #", "on page #", etc. The DocBook processor deals with generating the right text,
340 // including in the right language.
341 role = from_ascii(cmd);
343 if (cmd == "formatted") {
344 // A formatted reference may have many parameters. Generate all of them as roles, the only
345 // way arbitrary parameters can be passed into DocBook.
346 if (buffer().params().use_refstyle && getParam("caps") == "true")
347 role += " refstyle-caps";
348 if (buffer().params().use_refstyle && getParam("plural") == "true")
349 role += " refstyle-plural";
351 } else if (cmd == "eqref") {
352 display_before = from_ascii("(");
353 display_after = from_ascii(")");
355 // TODO: what about labelonly? I don't get how this is supposed to work...
358 // No name, ask DocBook to generate one.
359 docstring attr = from_utf8("linkend=\"") + xml::cleanID(ref) + from_utf8("\"");
361 attr += " role=\"" + role + "\"";
362 xs << display_before;
363 xs << xml::CompTag("xref", to_utf8(attr));
368 docstring InsetRef::xhtml(XMLStream & xs, OutputParams const & op) const
370 docstring const & ref = getParam("reference");
371 InsetLabel const * il = buffer().insetLabel(ref, true);
372 string const & cmd = params().getCmdName();
373 docstring display_string;
375 if (il && !il->counterValue().empty()) {
376 // Try to construct a label from the InsetLabel we reference.
377 docstring const & value = il->counterValue();
379 display_string = value;
380 else if (cmd == "vref")
381 // normally, would be "ref on page #", but we have no pages
382 display_string = value;
383 else if (cmd == "pageref" || cmd == "vpageref")
384 // normally would be "on page #", but we have no pages.
385 display_string = translateIfPossible(from_ascii("elsewhere"),
386 op.local_font->language()->lang());
387 else if (cmd == "eqref")
388 display_string = '(' + value + ')';
389 else if (cmd == "formatted") {
390 display_string = il->prettyCounter();
391 if (buffer().params().use_refstyle && getParam("caps") == "true")
392 capitalize(display_string);
393 // it is hard to see what to do about plurals...
395 else if (cmd == "nameref")
396 // FIXME We don't really have the ability to handle these
397 // properly in XHTML output yet (bug #8599).
398 // It might not be that hard to do. We have the InsetLabel,
399 // and we can presumably find its paragraph using the TOC.
400 // But the label might be referencing a section, yet not be
401 // in that section. So this is not trivial.
402 display_string = il->prettyCounter();
404 display_string = ref;
406 // FIXME What we'd really like to do is to be able to output some
407 // appropriate sort of text here. But to do that, we need to associate
408 // some sort of counter with the label, and we don't have that yet.
409 docstring const attr = "href=\"#" + xml::cleanAttr(ref) + '"';
410 xs << xml::StartTag("a", to_utf8(attr));
411 xs << display_string;
412 xs << xml::EndTag("a");
417 void InsetRef::toString(odocstream & os) const
419 odocstringstream ods;
420 plaintext(ods, OutputParams(nullptr));
425 void InsetRef::forOutliner(docstring & os, size_t const, bool const) const
427 // There's no need for details in the TOC, and a long label
428 // will just get in the way.
433 void InsetRef::updateBuffer(ParIterator const & it, UpdateType, bool const /*deleted*/)
435 docstring const & ref = getParam("reference");
437 // Check if this one is active (i.e., neither deleted with change-tracking
438 // nor in an inset that does not produce output, such as notes or inactive branches)
439 Paragraph const & para = it.paragraph();
440 active_ = !para.isDeleted(it.pos()) && para.inInset().producesOutput();
441 // If not, check whether we are in a deleted/non-outputting inset
443 for (size_type sl = 0 ; sl < it.depth() ; ++sl) {
444 Paragraph const & outer_par = it[sl].paragraph();
445 if (outer_par.isDeleted(it[sl].pos())
446 || !outer_par.inInset().producesOutput()) {
453 // register this inset into the buffer reference cache.
454 buffer().addReference(ref, this, it);
457 string const & cmd = getCmdName();
458 for (int i = 0; !types[i].latex_name.empty(); ++i) {
459 if (cmd == types[i].latex_name) {
460 label = _(types[i].short_gui_name);
465 if (cmd != "labelonly")
468 if (getParam("noprefix") != "true")
472 docstring suffix = split(ref, prefix, ':');
473 if (suffix.empty()) {
481 if (!buffer().params().isLatex() && !getParam("name").empty()) {
483 label += getParam("name");
486 unsigned int const maxLabelChars = 24;
487 if (label.size() > maxLabelChars) {
489 support::truncateWithEllipsis(label, maxLabelChars);
491 tooltip_ = from_ascii("");
493 screen_label_ = label;
499 docstring InsetRef::screenLabel() const
501 return (broken_ ? _("BROKEN: ") : docstring()) + screen_label_;
505 void InsetRef::addToToc(DocIterator const & cpit, bool output_active,
506 UpdateType, TocBackend & backend) const
508 active_ = output_active;
509 docstring const & label = getParam("reference");
510 if (buffer().insetLabel(label)) {
511 broken_ = !buffer().activeLabel(label) && active_;
513 if (broken_ && output_active) {
514 shared_ptr<Toc> toc2 = backend.toc("brokenrefs");
515 toc2->push_back(TocItem(cpit, 0, screenLabel(), output_active));
517 // This InsetRef has already been taken care of in InsetLabel::addToToc().
521 // It seems that this reference does not point to any valid label.
524 shared_ptr<Toc> toc = backend.toc("label");
525 toc->push_back(TocItem(cpit, 0, screenLabel(), output_active));
526 shared_ptr<Toc> toc2 = backend.toc("brokenrefs");
527 toc2->push_back(TocItem(cpit, 0, screenLabel(), output_active));
531 void InsetRef::validate(LaTeXFeatures & features) const
533 string const & cmd = getCmdName();
534 if (cmd == "vref" || cmd == "vpageref")
535 features.require("varioref");
536 else if (cmd == "formatted") {
537 docstring const data = getEscapedLabel(features.runparams());
540 bool const use_refstyle = buffer().params().use_refstyle;
541 bool const use_caps = getParam("caps") == "true";
542 docstring const fcmd =
543 getFormattedCmd(data, label, prefix, use_refstyle, use_caps);
545 features.require("refstyle");
547 features.addPreambleSnippet(from_ascii("\\let\\charef=\\chapref"));
548 else if (!prefix.empty()) {
549 docstring lcmd = "\\AtBeginDocument{\\providecommand" +
550 fcmd + "[1]{\\ref{" + prefix + ":#1}}}";
551 features.addPreambleSnippet(lcmd);
554 features.require("prettyref");
555 // prettyref uses "cha" for chapters, so we provide a kind of
557 if (prefix == "chap")
558 features.addPreambleSnippet(from_ascii("\\let\\pr@chap=\\pr@cha"));
560 } else if (cmd == "eqref" && !buffer().params().use_refstyle)
561 // with refstyle, we simply output "(\ref{label})"
562 features.require("amsmath");
563 else if (cmd == "nameref")
564 features.require("nameref");
567 bool InsetRef::forceLTR(OutputParams const & rp) const
569 // We force LTR for references. However,
570 // * Namerefs are output in the scripts direction
571 // at least with fontspec/bidi and luabidi, though (see #11518).
572 // * Parentheses are automatically swapped with XeTeX/bidi
573 // [not with LuaTeX/luabidi] (see #11626).
574 // FIXME: Re-Audit all other RTL cases.
575 if (rp.useBidiPackage())
577 return (getCmdName() != "nameref" || !buffer().masterParams().useNonTeXFonts);
581 InsetRef::type_info const InsetRef::types[] = {
582 { "ref", N_("Standard"), N_("Ref: ")},
583 { "eqref", N_("Equation"), N_("EqRef: ")},
584 { "pageref", N_("Page Number"), N_("Page: ")},
585 { "vpageref", N_("Textual Page Number"), N_("TextPage: ")},
586 { "vref", N_("Standard+Textual Page"), N_("Ref+Text: ")},
587 { "nameref", N_("Reference to Name"), N_("NameRef: ")},
588 { "formatted", N_("Formatted"), N_("Format: ")},
589 { "labelonly", N_("Label Only"), N_("Label: ")},
594 docstring InsetRef::getTOCString() const
596 docstring const & label = getParam("reference");
597 if (buffer().insetLabel(label))
598 broken_ = !buffer().activeLabel(label) && active_;
601 return tooltip_.empty() ? screenLabel() : tooltip_;