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 // Ctrl + click: go to label
107 if (cmd.action() == LFUN_MOUSE_RELEASE && cmd.modifier() == ControlModifier) {
108 lyx::dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
109 lyx::dispatch(FuncRequest(LFUN_LABEL_GOTO, getParam("reference")));
113 string const inset = cmd.getArg(0);
114 string const arg = cmd.getArg(1);
116 if (cmd.action() == LFUN_INSET_MODIFY && inset == "ref") {
117 if (arg == "toggle-plural")
119 else if (arg == "toggle-caps")
121 else if (arg == "toggle-noprefix")
122 pstring = "noprefix";
123 else if (arg == "changetarget") {
124 string const oldtarget = cmd.getArg(2);
125 string const newtarget = cmd.getArg(3);
126 if (!oldtarget.empty() && !newtarget.empty()
127 && getParam("reference") == from_utf8(oldtarget))
128 changeTarget(from_utf8(newtarget));
129 cur.forceBufferUpdate();
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"));
140 cur.forceBufferUpdate();
144 bool InsetRef::getStatus(Cursor & cur, FuncRequest const & cmd,
145 FuncStatus & status) const
147 if (cmd.action() != LFUN_INSET_MODIFY)
148 return InsetCommand::getStatus(cur, cmd, status);
149 if (cmd.getArg(0) != "ref")
150 return InsetCommand::getStatus(cur, cmd, status);
152 string const arg = cmd.getArg(1);
154 if (arg == "changetarget")
156 if (arg == "toggle-plural")
158 else if (arg == "toggle-caps")
160 if (!pstring.empty()) {
161 status.setEnabled(buffer().params().use_refstyle &&
162 params().getCmdName() == "formatted");
163 bool const isSet = (getParam(pstring) == "true");
164 status.setOnOff(isSet);
167 if (arg == "toggle-noprefix") {
168 status.setEnabled(params().getCmdName() == "labelonly");
169 bool const isSet = (getParam("noprefix") == "true");
170 status.setOnOff(isSet);
173 // otherwise not for us
174 return InsetCommand::getStatus(cur, cmd, status);
178 // the ref argument is the label name we are referencing.
179 // we expect ref to be in the form: pfx:suffix.
181 // if it isn't, then we can't produce a formatted reference,
182 // so we return "\ref" and put ref into label.
184 // for refstyle, we return "\pfxcmd", and put suffix into
185 // label and pfx into prefix. this is because refstyle expects
186 // the command: \pfxcmd{suffix}.
188 // for prettyref, we return "\prettyref" and put ref into label
189 // and pfx into prefix. this is because prettyref uses the whole
190 // label, thus: \prettyref{pfx:suffix}.
192 docstring InsetRef::getFormattedCmd(docstring const & ref,
193 docstring & label, docstring & prefix, bool use_refstyle,
196 static docstring const defcmd = from_ascii("\\ref");
197 static docstring const prtcmd = from_ascii("\\prettyref");
199 label = split(ref, prefix, ':');
201 // we have to have xxx:xxxxx...
203 LYXERR0("Label `" << ref << "' contains no `:' separator.");
205 prefix = from_ascii("");
209 if (prefix.empty()) {
211 LYXERR0("Label `" << ref << "' contains nothign before `:'.");
217 // \prettyref uses the whole label
222 // make sure the prefix is legal for a latex command
223 size_t const len = prefix.size();
224 for (size_t i = 0; i < len; i++) {
225 char_type const c = prefix[i];
226 if (!isAlphaASCII(c)) {
227 LYXERR0("Prefix `" << prefix << "' is invalid for LaTeX.");
234 prefix = support::capitalize(prefix);
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 (buffer().params().use_refstyle && cmd == "eqref") {
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 bool const use_caps = getParam("caps") == "true";
268 bool const use_plural = getParam("plural") == "true";
269 bool const use_refstyle = buffer().params().use_refstyle;
270 docstring const fcmd =
271 getFormattedCmd(data, label, prefix, use_refstyle, use_caps);
273 if (use_refstyle && use_plural)
275 os << '{' << label << '}';
277 else if (cmd == "labelonly") {
278 docstring const & ref = getParam("reference");
279 if (getParam("noprefix") != "true")
283 docstring suffix = split(ref, prefix, ':');
284 if (suffix.empty()) {
285 LYXERR0("Label `" << ref << "' contains no `:' separator.");
293 InsetCommandParams p(REF_CODE, cmd);
294 docstring const ref = getParam("reference");
295 p["reference"] = ref;
296 os << p.getCommand(rp);
299 if (rp.inulemcmd > 0)
304 int InsetRef::plaintext(odocstringstream & os,
305 OutputParams const &, size_t) const
307 docstring const str = getParam("reference");
308 os << '[' << str << ']';
309 return 2 + int(str.size());
313 void InsetRef::docbook(XMLStream & xs, OutputParams const &) const
315 docstring const & ref = getParam("reference");
316 InsetLabel const * il = buffer().insetLabel(ref, true);
317 string const & cmd = params().getCmdName();
318 docstring linkend = xml::cleanID(ref);
320 // A name is provided, LyX will provide it. This is supposed to be a very rare case.
321 // Link with linkend, as is it within the document (not outside, in which case xlink:href is better suited).
322 docstring const & name = getParam("name");
324 docstring attr = from_utf8("linkend=\"") + linkend + from_utf8("\"");
326 xs << xml::StartTag("link", to_utf8(attr));
328 xs << xml::EndTag("link");
332 // The DocBook processor will generate the name when required.
333 docstring display_before;
334 docstring display_after;
337 if (il && !il->counterValue().empty()) {
338 // Try to construct a label from the InsetLabel we reference.
339 if (cmd == "vref" || cmd == "pageref" || cmd == "vpageref" || cmd == "nameref" || cmd == "formatted") {
340 // "ref on page #", "on page #", etc. The DocBook processor deals with generating the right text,
341 // including in the right language.
342 role = from_ascii(cmd);
344 if (cmd == "formatted") {
345 // A formatted reference may have many parameters. Generate all of them as roles, the only
346 // way arbitrary parameters can be passed into DocBook.
347 if (buffer().params().use_refstyle && getParam("caps") == "true")
348 role += " refstyle-caps";
349 if (buffer().params().use_refstyle && getParam("plural") == "true")
350 role += " refstyle-plural";
352 } else if (cmd == "eqref") {
353 display_before = from_ascii("(");
354 display_after = from_ascii(")");
356 // TODO: what about labelonly? I don't get how this is supposed to work...
359 // No name, ask DocBook to generate one.
360 docstring attr = from_utf8("linkend=\"") + xml::cleanID(ref) + from_utf8("\"");
362 attr += " role=\"" + role + "\"";
363 xs << display_before;
364 xs << xml::CompTag("xref", to_utf8(attr));
369 docstring InsetRef::xhtml(XMLStream & xs, OutputParams const & op) const
371 docstring const & ref = getParam("reference");
372 InsetLabel const * il = buffer().insetLabel(ref, true);
373 string const & cmd = params().getCmdName();
374 docstring display_string;
376 if (il && !il->counterValue().empty()) {
377 // Try to construct a label from the InsetLabel we reference.
378 docstring const & value = il->counterValue();
380 display_string = value;
381 else if (cmd == "vref")
382 // normally, would be "ref on page #", but we have no pages
383 display_string = value;
384 else if (cmd == "pageref" || cmd == "vpageref")
385 // normally would be "on page #", but we have no pages.
386 display_string = translateIfPossible(from_ascii("elsewhere"),
387 op.local_font->language()->lang());
388 else if (cmd == "eqref")
389 display_string = '(' + value + ')';
390 else if (cmd == "formatted") {
391 display_string = il->prettyCounter();
392 if (buffer().params().use_refstyle && getParam("caps") == "true")
393 capitalize(display_string);
394 // it is hard to see what to do about plurals...
396 else if (cmd == "nameref")
397 // FIXME We don't really have the ability to handle these
398 // properly in XHTML output yet (bug #8599).
399 // It might not be that hard to do. We have the InsetLabel,
400 // and we can presumably find its paragraph using the TOC.
401 // But the label might be referencing a section, yet not be
402 // in that section. So this is not trivial.
403 display_string = il->prettyCounter();
405 display_string = ref;
407 // FIXME What we'd really like to do is to be able to output some
408 // appropriate sort of text here. But to do that, we need to associate
409 // some sort of counter with the label, and we don't have that yet.
410 docstring const attr = "href=\"#" + xml::cleanAttr(ref) + '"';
411 xs << xml::StartTag("a", to_utf8(attr));
412 xs << display_string;
413 xs << xml::EndTag("a");
418 void InsetRef::toString(odocstream & os) const
420 odocstringstream ods;
421 plaintext(ods, OutputParams(nullptr));
426 void InsetRef::forOutliner(docstring & os, size_t const, bool const) const
428 // It's hard to know what to do here. Should we show XREF in the TOC?
429 // Or should we just show that there is one? For now, we do the former.
430 odocstringstream ods;
431 plaintext(ods, OutputParams(nullptr));
436 void InsetRef::updateBuffer(ParIterator const & it, UpdateType, bool const /*deleted*/)
438 docstring const & ref = getParam("reference");
440 // Check if this one is active (i.e., neither deleted with change-tracking
441 // nor in an inset that does not produce output, such as notes or inactive branches)
442 Paragraph const & para = it.paragraph();
443 active_ = !para.isDeleted(it.pos()) && para.inInset().producesOutput();
444 // If not, check whether we are in a deleted/non-outputting inset
446 for (size_type sl = 0 ; sl < it.depth() ; ++sl) {
447 Paragraph const & outer_par = it[sl].paragraph();
448 if (outer_par.isDeleted(it[sl].pos())
449 || !outer_par.inInset().producesOutput()) {
456 // register this inset into the buffer reference cache.
457 buffer().addReference(ref, this, it);
460 string const & cmd = getCmdName();
461 for (int i = 0; !types[i].latex_name.empty(); ++i) {
462 if (cmd == types[i].latex_name) {
463 label = _(types[i].short_gui_name);
464 // indicate plural and caps
465 if (cmd == "formatted") {
466 bool const isPlural = getParam("plural") == "true";
467 bool const isCaps = getParam("caps") == "true";
469 label += from_ascii("+");
471 // up arrow (shift key) symbol
472 label += docstring(1, char_type(0x21E7));
475 label += from_ascii(": ");
480 if (cmd != "labelonly")
483 if (getParam("noprefix") != "true")
487 docstring suffix = split(ref, prefix, ':');
488 if (suffix.empty()) {
496 if (!buffer().params().isLatex() && !getParam("name").empty()) {
498 label += getParam("name");
501 unsigned int const maxLabelChars = 24;
502 if (label.size() > maxLabelChars) {
504 support::truncateWithEllipsis(label, maxLabelChars);
506 tooltip_ = from_ascii("");
508 screen_label_ = label;
514 docstring InsetRef::screenLabel() const
516 return (broken_ ? _("BROKEN: ") : docstring()) + screen_label_;
520 void InsetRef::addToToc(DocIterator const & cpit, bool output_active,
521 UpdateType, TocBackend & backend) const
523 active_ = output_active;
524 docstring const & label = getParam("reference");
525 if (buffer().insetLabel(label)) {
526 broken_ = !buffer().activeLabel(label) && active_;
528 if (broken_ && output_active) {
529 shared_ptr<Toc> toc2 = backend.toc("brokenrefs");
530 toc2->push_back(TocItem(cpit, 0, screenLabel(), output_active));
532 // This InsetRef has already been taken care of in InsetLabel::addToToc().
536 // It seems that this reference does not point to any valid label.
539 shared_ptr<Toc> toc = backend.toc("label");
540 if (TocBackend::findItem(*toc, 0, label) == toc->end())
541 toc->push_back(TocItem(cpit, 0, label, output_active, true));
542 toc->push_back(TocItem(cpit, 1, screenLabel(), output_active));
543 shared_ptr<Toc> toc2 = backend.toc("brokenrefs");
544 toc2->push_back(TocItem(cpit, 0, screenLabel(), output_active));
548 void InsetRef::validate(LaTeXFeatures & features) const
550 string const & cmd = getCmdName();
551 if (cmd == "vref" || cmd == "vpageref")
552 features.require("varioref");
553 else if (cmd == "formatted") {
554 docstring const data = getEscapedLabel(features.runparams());
557 bool const use_refstyle = buffer().params().use_refstyle;
558 bool const use_caps = getParam("caps") == "true";
559 docstring const fcmd =
560 getFormattedCmd(data, label, prefix, use_refstyle, use_caps);
562 features.require("refstyle");
564 features.addPreambleSnippet(from_ascii("\\let\\charef=\\chapref"));
565 else if (!prefix.empty()) {
566 docstring lcmd = "\\AtBeginDocument{\\providecommand" +
567 fcmd + "[1]{\\ref{" + prefix + ":#1}}}";
568 features.addPreambleSnippet(lcmd);
571 features.require("prettyref");
572 // prettyref uses "cha" for chapters, so we provide a kind of
574 if (prefix == "chap")
575 features.addPreambleSnippet(from_ascii("\\let\\pr@chap=\\pr@cha"));
577 } else if (cmd == "eqref" && !buffer().params().use_refstyle)
578 // with refstyle, we simply output "(\ref{label})"
579 features.require("amsmath");
580 else if (cmd == "nameref")
581 features.require("nameref");
584 bool InsetRef::forceLTR(OutputParams const & rp) const
586 // We force LTR for references. However,
587 // * Namerefs are output in the scripts direction
588 // at least with fontspec/bidi and luabidi, though (see #11518).
589 // * Parentheses are automatically swapped with XeTeX/bidi
590 // [not with LuaTeX/luabidi] (see #11626).
591 // FIXME: Re-Audit all other RTL cases.
592 if (rp.useBidiPackage())
594 return (getCmdName() != "nameref" || !buffer().masterParams().useNonTeXFonts);
598 InsetRef::type_info const InsetRef::types[] = {
599 { "ref", N_("Standard"), N_("Ref")},
600 { "eqref", N_("Equation"), N_("EqRef")},
601 { "pageref", N_("Page Number"), N_("Page")},
602 { "vpageref", N_("Textual Page Number"), N_("TextPage")},
603 { "vref", N_("Standard+Textual Page"), N_("Ref+Text")},
604 { "nameref", N_("Reference to Name"), N_("NameRef")},
605 { "formatted", N_("Formatted"), N_("Format")},
606 { "labelonly", N_("Label Only"), N_("Label")},
611 docstring InsetRef::getTOCString() const
613 docstring const & label = getParam("reference");
614 if (buffer().insetLabel(label))
615 broken_ = !buffer().activeLabel(label) && active_;
618 return tooltip_.empty() ? screenLabel() : tooltip_;