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 "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)
47 InsetRef::InsetRef(InsetRef const & ir)
48 : InsetCommand(ir), broken_(false)
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();
126 // otherwise not for us
128 return InsetCommand::doDispatch(cur, cmd);
130 bool const isSet = (getParam(pstring) == "true");
131 setParam(pstring, from_ascii(isSet ? "false" : "true"));
135 bool InsetRef::getStatus(Cursor & cur, FuncRequest const & cmd,
136 FuncStatus & status) const
138 if (cmd.action() != LFUN_INSET_MODIFY)
139 return InsetCommand::getStatus(cur, cmd, status);
140 if (cmd.getArg(0) != "ref")
141 return InsetCommand::getStatus(cur, cmd, status);
143 string const arg = cmd.getArg(1);
145 if (arg == "changetarget")
147 if (arg == "toggle-plural")
149 else if (arg == "toggle-caps")
151 if (!pstring.empty()) {
152 status.setEnabled(buffer().params().use_refstyle &&
153 params().getCmdName() == "formatted");
154 bool const isSet = (getParam(pstring) == "true");
155 status.setOnOff(isSet);
158 if (arg == "toggle-noprefix") {
159 status.setEnabled(params().getCmdName() == "labelonly");
160 bool const isSet = (getParam("noprefix") == "true");
161 status.setOnOff(isSet);
164 // otherwise not for us
165 return InsetCommand::getStatus(cur, cmd, status);
171 void capitalize(docstring & s) {
172 char_type t = uppercase(s[0]);
179 // the ref argument is the label name we are referencing.
180 // we expect ref to be in the form: pfx:suffix.
182 // if it isn't, then we can't produce a formatted reference,
183 // so we return "\ref" and put ref into label.
185 // for refstyle, we return "\pfxcmd", and put suffix into
186 // label and pfx into prefix. this is because refstyle expects
187 // the command: \pfxcmd{suffix}.
189 // for prettyref, we return "\prettyref" and put ref into label
190 // and pfx into prefix. this is because prettyref uses the whole
191 // label, thus: \prettyref{pfx:suffix}.
193 docstring InsetRef::getFormattedCmd(docstring const & ref,
194 docstring & label, docstring & prefix, docstring const & caps) const
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()) {
215 if (!buffer().params().use_refstyle) {
216 // \prettyref uses the whole label
221 // make sure the prefix is legal for a latex command
222 int const len = prefix.size();
223 for (int i = 0; i < len; i++) {
224 char_type const c = prefix[i];
225 if (!isAlphaASCII(c)) {
226 LYXERR0("Prefix `" << prefix << "' is invalid for LaTeX.");
232 if (caps == "true") {
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 (cmd == "eqref" && buffer().params().use_refstyle) {
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 docstring const fcmd =
267 getFormattedCmd(data, label, prefix, getParam("caps"));
269 if (buffer().params().use_refstyle && getParam("plural") == "true")
271 os << '{' << label << '}';
273 else if (cmd == "labelonly") {
274 docstring const & ref = getParam("reference");
275 if (getParam("noprefix") != "true")
279 docstring suffix = split(ref, prefix, ':');
280 if (suffix.empty()) {
281 LYXERR0("Label `" << ref << "' contains no `:' separator.");
289 // We don't want to output p_["name"], since that is only used
290 // in docbook. So we construct new params, without it, and use that.
291 InsetCommandParams p(REF_CODE, cmd);
292 docstring const ref = getParam("reference");
293 p["reference"] = ref;
294 os << p.getCommand(rp);
297 if (rp.inulemcmd > 0)
302 int InsetRef::plaintext(odocstringstream & os,
303 OutputParams const &, size_t) const
305 docstring const str = getParam("reference");
306 os << '[' << str << ']';
307 return 2 + str.size();
311 int InsetRef::docbook(odocstream & os, OutputParams const & runparams) const
313 docstring const & name = getParam("name");
315 if (runparams.flavor == OutputParams::XML) {
316 os << "<xref linkend=\""
317 << sgml::cleanID(buffer(), runparams, getParam("reference"))
320 os << "<xref linkend=\""
321 << sgml::cleanID(buffer(), runparams, getParam("reference"))
325 os << "<link linkend=\""
326 << sgml::cleanID(buffer(), runparams, getParam("reference"))
336 docstring InsetRef::xhtml(XHTMLStream & xs, OutputParams const & op) const
338 docstring const & ref = getParam("reference");
339 InsetLabel const * il = buffer().insetLabel(ref, true);
340 string const & cmd = params().getCmdName();
341 docstring display_string;
343 if (il && !il->counterValue().empty()) {
344 // Try to construct a label from the InsetLabel we reference.
345 docstring const & value = il->counterValue();
347 display_string = value;
348 else if (cmd == "vref")
349 // normally, would be "ref on page #", but we have no pages
350 display_string = value;
351 else if (cmd == "pageref" || cmd == "vpageref")
352 // normally would be "on page #", but we have no pages.
353 display_string = translateIfPossible(from_ascii("elsewhere"),
354 op.local_font->language()->lang());
355 else if (cmd == "eqref")
356 display_string = '(' + value + ')';
357 else if (cmd == "formatted") {
358 display_string = il->prettyCounter();
359 if (buffer().params().use_refstyle && getParam("caps") == "true")
360 capitalize(display_string);
361 // it is hard to see what to do about plurals...
363 else if (cmd == "nameref")
364 // FIXME We don't really have the ability to handle these
365 // properly in XHTML output yet (bug #8599).
366 // It might not be that hard to do. We have the InsetLabel,
367 // and we can presumably find its paragraph using the TOC.
368 // But the label might be referencing a section, yet not be
369 // in that section. So this is not trivial.
370 display_string = il->prettyCounter();
372 display_string = ref;
374 // FIXME What we'd really like to do is to be able to output some
375 // appropriate sort of text here. But to do that, we need to associate
376 // some sort of counter with the label, and we don't have that yet.
377 docstring const attr = "href=\"#" + html::cleanAttr(ref) + '"';
378 xs << html::StartTag("a", to_utf8(attr));
379 xs << display_string;
380 xs << html::EndTag("a");
385 void InsetRef::toString(odocstream & os) const
387 odocstringstream ods;
388 plaintext(ods, OutputParams(0));
393 void InsetRef::forOutliner(docstring & os, size_t const, bool const) const
395 // There's no need for details in the TOC, and a long label
396 // will just get in the way.
401 void InsetRef::updateBuffer(ParIterator const & it, UpdateType)
403 docstring const & ref = getParam("reference");
404 // register this inset into the buffer reference cache.
405 buffer().addReference(ref, this, it);
408 string const & cmd = getCmdName();
409 for (int i = 0; !types[i].latex_name.empty(); ++i) {
410 if (cmd == types[i].latex_name) {
411 label = _(types[i].short_gui_name);
416 if (cmd != "labelonly")
419 if (getParam("noprefix") != "true")
423 docstring suffix = split(ref, prefix, ':');
424 if (suffix.empty()) {
432 if (!buffer().params().isLatex() && !getParam("name").empty()) {
434 label += getParam("name");
437 unsigned int const maxLabelChars = 24;
438 if (label.size() > maxLabelChars) {
440 support::truncateWithEllipsis(label, maxLabelChars);
442 tooltip_ = from_ascii("");
444 screen_label_ = label;
449 docstring InsetRef::screenLabel() const
451 return (broken_ ? _("BROKEN: ") : docstring()) + screen_label_;
455 void InsetRef::addToToc(DocIterator const & cpit, bool output_active,
456 UpdateType, TocBackend & backend) const
458 docstring const & label = getParam("reference");
459 if (buffer().insetLabel(label)) {
460 broken_ = !buffer().activeLabel(label);
461 // This InsetRef has already been taken care of in InsetLabel::addToToc().
465 // It seems that this reference does not point to any valid label.
468 shared_ptr<Toc> toc = backend.toc("label");
469 toc->push_back(TocItem(cpit, 0, screenLabel(), output_active));
473 void InsetRef::validate(LaTeXFeatures & features) const
475 string const cmd = getCmdName();
476 if (cmd == "vref" || cmd == "vpageref")
477 features.require("varioref");
478 else if (cmd == "formatted") {
479 docstring const data = getEscapedLabel(features.runparams());
482 docstring const fcmd =
483 getFormattedCmd(data, label, prefix, getParam("caps"));
484 if (buffer().params().use_refstyle) {
485 features.require("refstyle");
487 features.addPreambleSnippet(from_ascii("\\let\\charef=\\chapref"));
488 else if (!prefix.empty()) {
489 docstring lcmd = "\\AtBeginDocument{\\providecommand" +
490 fcmd + "[1]{\\ref{" + prefix + ":#1}}}";
491 features.addPreambleSnippet(lcmd);
494 features.require("prettyref");
495 // prettyref uses "cha" for chapters, so we provide a kind of
497 if (prefix == "chap")
498 features.addPreambleSnippet(from_ascii("\\let\\pr@chap=\\pr@cha"));
500 } else if (cmd == "eqref" && !buffer().params().use_refstyle)
501 // with refstyle, we simply output "(\ref{label})"
502 features.require("amsmath");
503 else if (cmd == "nameref")
504 features.require("nameref");
507 bool InsetRef::forceLTR(OutputParams const & rp) const
509 // We force LTR for references. However,
510 // * Namerefs are output in the scripts direction
511 // at least with fontspec/bidi and luabidi, though (see #11518).
512 // * Parentheses are automatically swapped with XeTeX/bidi
513 // [not with LuaTeX/luabidi] (see #11626).
514 // FIXME: Re-Audit all other RTL cases.
515 if (rp.useBidiPackage())
517 return (getCmdName() != "nameref" || !buffer().masterParams().useNonTeXFonts);
521 InsetRef::type_info const InsetRef::types[] = {
522 { "ref", N_("Standard"), N_("Ref: ")},
523 { "eqref", N_("Equation"), N_("EqRef: ")},
524 { "pageref", N_("Page Number"), N_("Page: ")},
525 { "vpageref", N_("Textual Page Number"), N_("TextPage: ")},
526 { "vref", N_("Standard+Textual Page"), N_("Ref+Text: ")},
527 { "nameref", N_("Reference to Name"), N_("NameRef: ")},
528 { "formatted", N_("Formatted"), N_("Format: ")},
529 { "labelonly", N_("Label Only"), N_("Label: ")},
534 docstring InsetRef::getTOCString() const
536 return tooltip_.empty() ? screenLabel() : tooltip_;