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();
128 // Ctrl + click: go to label
129 if (cmd.action() == LFUN_MOUSE_RELEASE && cmd.modifier() == ControlModifier) {
130 lyx::dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
131 lyx::dispatch(FuncRequest(LFUN_LABEL_GOTO, getParam("reference")));
135 // otherwise not for us
137 return InsetCommand::doDispatch(cur, cmd);
139 bool const isSet = (getParam(pstring) == "true");
140 setParam(pstring, from_ascii(isSet ? "false" : "true"));
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);
180 void capitalize(docstring & s) {
181 char_type t = uppercase(s[0]);
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, docstring const & caps) const
205 static docstring const defcmd = from_ascii("\\ref");
206 static docstring const prtcmd = from_ascii("\\prettyref");
208 label = split(ref, prefix, ':');
210 // we have to have xxx:xxxxx...
212 LYXERR0("Label `" << ref << "' contains no `:' separator.");
214 prefix = from_ascii("");
218 if (prefix.empty()) {
224 if (!buffer().params().use_refstyle) {
225 // \prettyref uses the whole label
230 // make sure the prefix is legal for a latex command
231 size_t const len = prefix.size();
232 for (size_t i = 0; i < len; i++) {
233 char_type const c = prefix[i];
234 if (!isAlphaASCII(c)) {
235 LYXERR0("Prefix `" << prefix << "' is invalid for LaTeX.");
241 if (caps == "true") {
244 return from_ascii("\\") + prefix + from_ascii("ref");
248 docstring InsetRef::getEscapedLabel(OutputParams const & rp) const
250 InsetCommandParams const & p = params();
251 ParamInfo const & pi = p.info();
252 ParamInfo::ParamData const & pd = pi["reference"];
253 return p.prepareCommand(rp, getParam("reference"), pd.handling());
257 void InsetRef::latex(otexstream & os, OutputParams const & rp) const
259 string const & cmd = getCmdName();
260 docstring const & data = getEscapedLabel(rp);
262 if (rp.inulemcmd > 0)
265 if (cmd == "eqref" && buffer().params().use_refstyle) {
266 // we advertise this as printing "(n)", so we'll do that, at least
267 // for refstyle, since refstlye's own \eqref prints, by default,
268 // "equation n". if one wants \eqref, one can get it by using a
269 // formatted label in this case.
270 os << '(' << from_ascii("\\ref{") << data << from_ascii("})");
272 else if (cmd == "formatted") {
275 docstring const fcmd =
276 getFormattedCmd(data, label, prefix, getParam("caps"));
278 if (buffer().params().use_refstyle && getParam("plural") == "true")
280 os << '{' << label << '}';
282 else if (cmd == "labelonly") {
283 docstring const & ref = getParam("reference");
284 if (getParam("noprefix") != "true")
288 docstring suffix = split(ref, prefix, ':');
289 if (suffix.empty()) {
290 LYXERR0("Label `" << ref << "' contains no `:' separator.");
298 InsetCommandParams p(REF_CODE, cmd);
299 docstring const ref = getParam("reference");
300 p["reference"] = ref;
301 os << p.getCommand(rp);
304 if (rp.inulemcmd > 0)
309 int InsetRef::plaintext(odocstringstream & os,
310 OutputParams const &, size_t) const
312 docstring const str = getParam("reference");
313 os << '[' << str << ']';
314 return 2 + int(str.size());
318 void InsetRef::docbook(XMLStream & xs, OutputParams const &) const
320 docstring const & ref = getParam("reference");
321 InsetLabel const * il = buffer().insetLabel(ref, true);
322 string const & cmd = params().getCmdName();
323 docstring linkend = xml::cleanID(ref);
325 // A name is provided, LyX will provide it. This is supposed to be a very rare case.
326 // Link with linkend, as is it within the document (not outside, in which case xlink:href is better suited).
327 docstring const & name = getParam("name");
329 docstring attr = from_utf8("linkend=\"") + linkend + from_utf8("\"");
331 xs << xml::StartTag("link", to_utf8(attr));
333 xs << xml::EndTag("link");
337 // The DocBook processor will generate the name when required.
338 docstring display_before;
339 docstring display_after;
342 if (il && !il->counterValue().empty()) {
343 // Try to construct a label from the InsetLabel we reference.
344 if (cmd == "vref" || cmd == "pageref" || cmd == "vpageref" || cmd == "nameref" || cmd == "formatted") {
345 // "ref on page #", "on page #", etc. The DocBook processor deals with generating the right text,
346 // including in the right language.
347 role = from_ascii(cmd);
349 if (cmd == "formatted") {
350 // A formatted reference may have many parameters. Generate all of them as roles, the only
351 // way arbitrary parameters can be passed into DocBook.
352 if (buffer().params().use_refstyle && getParam("caps") == "true")
353 role += " refstyle-caps";
354 if (buffer().params().use_refstyle && getParam("plural") == "true")
355 role += " refstyle-plural";
357 } else if (cmd == "eqref") {
358 display_before = from_ascii("(");
359 display_after = from_ascii(")");
361 // TODO: what about labelonly? I don't get how this is supposed to work...
364 // No name, ask DocBook to generate one.
365 docstring attr = from_utf8("linkend=\"") + xml::cleanID(ref) + from_utf8("\"");
367 attr += " role=\"" + role + "\"";
368 xs << display_before;
369 xs << xml::CompTag("xref", to_utf8(attr));
374 docstring InsetRef::xhtml(XMLStream & xs, OutputParams const & op) const
376 docstring const & ref = getParam("reference");
377 InsetLabel const * il = buffer().insetLabel(ref, true);
378 string const & cmd = params().getCmdName();
379 docstring display_string;
381 if (il && !il->counterValue().empty()) {
382 // Try to construct a label from the InsetLabel we reference.
383 docstring const & value = il->counterValue();
385 display_string = value;
386 else if (cmd == "vref")
387 // normally, would be "ref on page #", but we have no pages
388 display_string = value;
389 else if (cmd == "pageref" || cmd == "vpageref")
390 // normally would be "on page #", but we have no pages.
391 display_string = translateIfPossible(from_ascii("elsewhere"),
392 op.local_font->language()->lang());
393 else if (cmd == "eqref")
394 display_string = '(' + value + ')';
395 else if (cmd == "formatted") {
396 display_string = il->prettyCounter();
397 if (buffer().params().use_refstyle && getParam("caps") == "true")
398 capitalize(display_string);
399 // it is hard to see what to do about plurals...
401 else if (cmd == "nameref")
402 // FIXME We don't really have the ability to handle these
403 // properly in XHTML output yet (bug #8599).
404 // It might not be that hard to do. We have the InsetLabel,
405 // and we can presumably find its paragraph using the TOC.
406 // But the label might be referencing a section, yet not be
407 // in that section. So this is not trivial.
408 display_string = il->prettyCounter();
410 display_string = ref;
412 // FIXME What we'd really like to do is to be able to output some
413 // appropriate sort of text here. But to do that, we need to associate
414 // some sort of counter with the label, and we don't have that yet.
415 docstring const attr = "href=\"#" + xml::cleanAttr(ref) + '"';
416 xs << xml::StartTag("a", to_utf8(attr));
417 xs << display_string;
418 xs << xml::EndTag("a");
423 void InsetRef::toString(odocstream & os) const
425 odocstringstream ods;
426 plaintext(ods, OutputParams(nullptr));
431 void InsetRef::forOutliner(docstring & os, size_t const, bool const) const
433 // There's no need for details in the TOC, and a long label
434 // will just get in the way.
439 void InsetRef::updateBuffer(ParIterator const & it, UpdateType, bool const /*deleted*/)
441 docstring const & ref = getParam("reference");
443 // Check if this one is active (i.e., neither deleted with change-tracking
444 // nor in an inset that does not produce output, such as notes or inactive branches)
445 Paragraph const & para = it.paragraph();
446 active_ = !para.isDeleted(it.pos()) && para.inInset().producesOutput();
447 // If not, check whether we are in a deleted/non-outputting inset
449 for (size_type sl = 0 ; sl < it.depth() ; ++sl) {
450 Paragraph const & outer_par = it[sl].paragraph();
451 if (outer_par.isDeleted(it[sl].pos())
452 || !outer_par.inInset().producesOutput()) {
459 // register this inset into the buffer reference cache.
460 buffer().addReference(ref, this, it);
463 string const & cmd = getCmdName();
464 for (int i = 0; !types[i].latex_name.empty(); ++i) {
465 if (cmd == types[i].latex_name) {
466 label = _(types[i].short_gui_name);
471 if (cmd != "labelonly")
474 if (getParam("noprefix") != "true")
478 docstring suffix = split(ref, prefix, ':');
479 if (suffix.empty()) {
487 if (!buffer().params().isLatex() && !getParam("name").empty()) {
489 label += getParam("name");
492 unsigned int const maxLabelChars = 24;
493 if (label.size() > maxLabelChars) {
495 support::truncateWithEllipsis(label, maxLabelChars);
497 tooltip_ = from_ascii("");
499 screen_label_ = label;
505 docstring InsetRef::screenLabel() const
507 return (broken_ ? _("BROKEN: ") : docstring()) + screen_label_;
511 void InsetRef::addToToc(DocIterator const & cpit, bool output_active,
512 UpdateType, TocBackend & backend) const
514 active_ = output_active;
515 docstring const & label = getParam("reference");
516 if (buffer().insetLabel(label)) {
517 broken_ = !buffer().activeLabel(label) && active_;
519 if (broken_ && output_active) {
520 shared_ptr<Toc> toc2 = backend.toc("brokenrefs");
521 toc2->push_back(TocItem(cpit, 0, screenLabel(), output_active));
523 // This InsetRef has already been taken care of in InsetLabel::addToToc().
527 // It seems that this reference does not point to any valid label.
530 shared_ptr<Toc> toc = backend.toc("label");
531 toc->push_back(TocItem(cpit, 0, screenLabel(), output_active));
532 shared_ptr<Toc> toc2 = backend.toc("brokenrefs");
533 toc2->push_back(TocItem(cpit, 0, screenLabel(), output_active));
537 void InsetRef::validate(LaTeXFeatures & features) const
539 string const & cmd = getCmdName();
540 if (cmd == "vref" || cmd == "vpageref")
541 features.require("varioref");
542 else if (cmd == "formatted") {
543 docstring const data = getEscapedLabel(features.runparams());
546 docstring const fcmd =
547 getFormattedCmd(data, label, prefix, getParam("caps"));
548 if (buffer().params().use_refstyle) {
549 features.require("refstyle");
551 features.addPreambleSnippet(from_ascii("\\let\\charef=\\chapref"));
552 else if (!prefix.empty()) {
553 docstring lcmd = "\\AtBeginDocument{\\providecommand" +
554 fcmd + "[1]{\\ref{" + prefix + ":#1}}}";
555 features.addPreambleSnippet(lcmd);
558 features.require("prettyref");
559 // prettyref uses "cha" for chapters, so we provide a kind of
561 if (prefix == "chap")
562 features.addPreambleSnippet(from_ascii("\\let\\pr@chap=\\pr@cha"));
564 } else if (cmd == "eqref" && !buffer().params().use_refstyle)
565 // with refstyle, we simply output "(\ref{label})"
566 features.require("amsmath");
567 else if (cmd == "nameref")
568 features.require("nameref");
571 bool InsetRef::forceLTR(OutputParams const & rp) const
573 // We force LTR for references. However,
574 // * Namerefs are output in the scripts direction
575 // at least with fontspec/bidi and luabidi, though (see #11518).
576 // * Parentheses are automatically swapped with XeTeX/bidi
577 // [not with LuaTeX/luabidi] (see #11626).
578 // FIXME: Re-Audit all other RTL cases.
579 if (rp.useBidiPackage())
581 return (getCmdName() != "nameref" || !buffer().masterParams().useNonTeXFonts);
585 InsetRef::type_info const InsetRef::types[] = {
586 { "ref", N_("Standard"), N_("Ref: ")},
587 { "eqref", N_("Equation"), N_("EqRef: ")},
588 { "pageref", N_("Page Number"), N_("Page: ")},
589 { "vpageref", N_("Textual Page Number"), N_("TextPage: ")},
590 { "vref", N_("Standard+Textual Page"), N_("Ref+Text: ")},
591 { "nameref", N_("Reference to Name"), N_("NameRef: ")},
592 { "formatted", N_("Formatted"), N_("Format: ")},
593 { "labelonly", N_("Label Only"), N_("Label: ")},
598 docstring InsetRef::getTOCString() const
600 docstring const & label = getParam("reference");
601 if (buffer().insetLabel(label))
602 broken_ = !buffer().activeLabel(label) && active_;
605 return tooltip_.empty() ? screenLabel() : tooltip_;