]> git.lyx.org Git - lyx.git/blob - src/insets/InsetRef.cpp
Fix bug #12772
[lyx.git] / src / insets / InsetRef.cpp
1 /**
2  * \file InsetRef.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author José Matos
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10 #include <config.h>
11
12 #include "InsetRef.h"
13
14 #include "Buffer.h"
15 #include "BufferParams.h"
16 #include "Cursor.h"
17 #include "DispatchResult.h"
18 #include "FuncStatus.h"
19 #include "InsetLabel.h"
20 #include "Language.h"
21 #include "LaTeXFeatures.h"
22 #include "LyX.h"
23 #include "output_xhtml.h"
24 #include "Paragraph.h"
25 #include "ParIterator.h"
26 #include "PDFOptions.h"
27 #include "xml.h"
28 #include "texstream.h"
29 #include "TocBackend.h"
30
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"
36
37 using namespace lyx::support;
38 using namespace std;
39
40 namespace lyx {
41
42
43 InsetRef::InsetRef(Buffer * buf, InsetCommandParams const & p)
44         : InsetCommand(buf, p), broken_(false), active_(true)
45 {}
46
47
48 InsetRef::InsetRef(InsetRef const & ir)
49         : InsetCommand(ir), broken_(false), active_(true)
50 {}
51
52
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.
56         return s == "ref"
57                 || s == "pageref"
58                 || s == "vref"
59                 || s == "vpageref"
60                 || s == "formatted"
61                 || s == "prettyref" // for InsetMathRef FIXME
62                 || s == "eqref"
63                 || s == "nameref"
64                 || s == "labelonly";
65 }
66
67
68 ParamInfo const & InsetRef::findInfo(string const & /* cmdName */)
69 {
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);
79         }
80         return param_info_;
81 }
82
83
84 docstring InsetRef::layoutName() const
85 {
86         return from_ascii("Ref");
87 }
88
89
90 void InsetRef::changeTarget(docstring const & new_label)
91 {
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));
100         } else
101                 setParam("reference", new_label);
102 }
103
104
105
106 void InsetRef::doDispatch(Cursor & cur, FuncRequest & cmd)
107 {
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")));
112                         return;
113                 }
114
115         string const inset = cmd.getArg(0);
116         string const arg   = cmd.getArg(1);
117         string pstring;
118         if (cmd.action() == LFUN_INSET_MODIFY && inset == "ref") {
119                 if (arg == "toggle-plural")
120                         pstring = "plural";
121                 else if (arg == "toggle-caps")
122                         pstring = "caps";
123                 else if (arg == "toggle-noprefix")
124                         pstring = "noprefix";
125                 else if (arg == "toggle-nolink")
126                         pstring = "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();
134                         return;
135                 }
136         }
137
138         // otherwise not for us
139         if (pstring.empty())
140                 return InsetCommand::doDispatch(cur, cmd);
141
142         bool const isSet = (getParam(pstring) == "true");
143         setParam(pstring, from_ascii(isSet ? "false"  : "true"));
144         cur.forceBufferUpdate();
145 }
146
147
148 bool InsetRef::getStatus(Cursor & cur, FuncRequest const & cmd,
149         FuncStatus & status) const
150 {
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);
155
156         string const arg = cmd.getArg(1);
157         string pstring;
158         if (arg == "changetarget")
159                 return true;
160         if (arg == "toggle-plural")
161                 pstring = "plural";
162         else if (arg == "toggle-caps")
163                 pstring = "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);
169                 return true;
170         }
171         if (arg == "toggle-noprefix") {
172                 status.setEnabled(params().getCmdName() == "labelonly");
173                 bool const isSet = (getParam("noprefix") == "true");
174                 status.setOnOff(isSet);
175                 return true;
176         }
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);
181                 return true;
182         }
183         // otherwise not for us
184         return InsetCommand::getStatus(cur, cmd, status);
185 }
186
187
188 // the ref argument is the label name we are referencing.
189 // we expect ref to be in the form: pfx:suffix.
190 //
191 // if it isn't, then we can't produce a formatted reference,
192 // so we return "\ref" and put ref into label.
193 //
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}.
197 //
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}.
201 //
202 docstring InsetRef::getFormattedCmd(docstring const & ref,
203         docstring & label, docstring & prefix, bool use_refstyle,
204         bool use_caps)
205 {
206         static docstring const defcmd = from_ascii("\\ref");
207         static docstring const prtcmd = from_ascii("\\prettyref");
208
209         label = split(ref, prefix, ':');
210
211         // we have to have xxx:xxxxx...
212         if (label.empty()) {
213                 LYXERR0("Label `" << ref << "' contains no `:' separator.");
214                 label = ref;
215                 prefix = from_ascii("");
216                 return defcmd;
217         }
218
219         if (prefix.empty()) {
220                 // we have ":xxxx"
221                 LYXERR0("Label `" << ref << "' contains nothign before `:'.");
222                 label = ref;
223                 return defcmd;
224         }
225
226         if (!use_refstyle) {
227                 // \prettyref uses the whole label
228                 label = ref;
229                 return prtcmd;
230         }
231
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.");
238                         // restore the label
239                         label = ref;
240                         return defcmd;
241                 }
242         }
243         if (use_caps) {
244                 prefix = support::capitalize(prefix);
245         }
246         return from_ascii("\\") + prefix + from_ascii("ref");
247 }
248
249
250 docstring InsetRef::getEscapedLabel(OutputParams const & rp) const
251 {
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());
256 }
257
258
259 void InsetRef::latex(otexstream & os, OutputParams const & rp) const
260 {
261         string const & cmd = getCmdName();
262         docstring const & data = getEscapedLabel(rp);
263         bool const hyper_on = buffer().params().pdfoptions().use_hyperref;
264
265         if (rp.inulemcmd > 0)
266                 os << "\\mbox{";
267
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("})");
278         }
279         else if (cmd == "formatted") {
280                 docstring label;
281                 docstring prefix;
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);
287                 os << fcmd;
288                 if (use_refstyle && use_plural)
289                     os << "[s]";
290                 os << '{' << label << '}';
291         }
292         else if (cmd == "labelonly") {
293                 docstring const & ref = getParam("reference");
294                 if (getParam("noprefix") != "true")
295                         os << ref;
296                 else {
297                         docstring prefix;
298                         docstring suffix = split(ref, prefix, ':');
299                         if (suffix.empty()) {
300                     LYXERR0("Label `" << ref << "' contains no `:' separator.");
301                                 os << ref;
302                         } else {
303                                 os << suffix;
304                         }
305                 }
306         }
307         else {
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);
313         }
314
315         if (rp.inulemcmd > 0)
316                 os << "}";
317 }
318
319
320 int InsetRef::plaintext(odocstringstream & os,
321         OutputParams const &, size_t) const
322 {
323         docstring const str = getParam("reference");
324         os << '[' << str << ']';
325         return 2 + int(str.size());
326 }
327
328
329 void InsetRef::docbook(XMLStream & xs, OutputParams const &) const
330 {
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);
335
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");
339         if (!name.empty()) {
340                 docstring attr = from_utf8("linkend=\"") + linkend + from_utf8("\"");
341
342                 xs << xml::StartTag("link", to_utf8(attr));
343                 xs << name;
344                 xs << xml::EndTag("link");
345                 return;
346         }
347
348         // The DocBook processor will generate the name when required.
349         docstring display_before;
350         docstring display_after;
351         docstring role;
352
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);
359
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";
367                         }
368                 } else if (cmd == "eqref") {
369                         display_before = from_ascii("(");
370                         display_after = from_ascii(")");
371                 }
372                 // TODO: what about labelonly? I don't get how this is supposed to work...
373         }
374
375         // No name, ask DocBook to generate one.
376         docstring attr = from_utf8("linkend=\"") + xml::cleanID(ref) + from_utf8("\"");
377         if (!role.empty())
378                 attr += " role=\"" + role + "\"";
379         xs << display_before;
380         xs << xml::CompTag("xref", to_utf8(attr));
381         xs << display_after;
382 }
383
384
385 docstring InsetRef::xhtml(XMLStream & xs, OutputParams const & op) const
386 {
387         docstring const & ref = getParam("reference");
388         InsetLabel const * il = buffer().insetLabel(ref, true);
389         string const & cmd = params().getCmdName();
390         docstring display_string;
391
392         if (il && !il->counterValue().empty()) {
393                 // Try to construct a label from the InsetLabel we reference.
394                 docstring const & value = il->counterValue();
395                 if (cmd == "ref")
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...
411                 }
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();
420         } else
421                         display_string = ref;
422
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");
430         return docstring();
431 }
432
433
434 void InsetRef::toString(odocstream & os) const
435 {
436         odocstringstream ods;
437         plaintext(ods, OutputParams(nullptr));
438         os << ods.str();
439 }
440
441
442 void InsetRef::forOutliner(docstring & os, size_t const, bool const) const
443 {
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));
448         os += ods.str();
449 }
450
451
452 void InsetRef::updateBuffer(ParIterator const & it, UpdateType, bool const /*deleted*/)
453 {
454         docstring const & ref = getParam("reference");
455
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
461         if (active_) {
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()) {
466                                 active_ = false;
467                                 break;
468                         }
469                 }
470         }
471
472         // register this inset into the buffer reference cache.
473         buffer().addReference(ref, this, it);
474
475         docstring label;
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";
483                                 if (isNoLink)
484                                         label += from_ascii("*");
485                         }
486                         // indicate plural and caps
487                         if (cmd == "formatted") {
488                                 bool const isPlural = getParam("plural") == "true";
489                                 bool const isCaps = getParam("caps") == "true";
490                                 if (isPlural)
491                                         label += from_ascii("+");
492                                 if (isCaps) {
493                                         // up arrow (shift key) symbol
494                                         label += docstring(1, char_type(0x21E7));
495                                 }
496                         }
497                         label += from_ascii(": ");
498                         break;
499                 }
500         }
501
502         if (cmd != "labelonly")
503                 label += ref;
504         else {
505                 if (getParam("noprefix") != "true")
506                         label += ref;
507                 else {
508                         docstring prefix;
509                         docstring suffix = split(ref, prefix, ':');
510                         if (suffix.empty()) {
511                                 label += ref;
512                         } else {
513                                 label += suffix;
514                         }
515                 }
516         }
517
518         if (!buffer().params().isLatex() && !getParam("name").empty()) {
519                 label += "||";
520                 label += getParam("name");
521         }
522
523         unsigned int const maxLabelChars = 24;
524         if (label.size() > maxLabelChars) {
525                 tooltip_ = label;
526                 support::truncateWithEllipsis(label, maxLabelChars);
527         } else
528                 tooltip_ = from_ascii("");
529
530         screen_label_ = label;
531         broken_ = false;
532         setBroken(broken_);
533 }
534
535
536 docstring InsetRef::screenLabel() const
537 {
538         return (broken_ ? _("BROKEN: ") : docstring()) + screen_label_;
539 }
540
541
542 void InsetRef::addToToc(DocIterator const & cpit, bool output_active,
543                         UpdateType, TocBackend & backend) const
544 {
545         active_ = output_active;
546         docstring const & label = getParam("reference");
547         if (buffer().insetLabel(label)) {
548                 broken_ = !buffer().activeLabel(label) && active_;
549                 setBroken(broken_);
550                 if (broken_ && output_active) {
551                         shared_ptr<Toc> toc2 = backend.toc("brokenrefs");
552                         toc2->push_back(TocItem(cpit, 0, screenLabel(), output_active));
553                 }
554                 // This InsetRef has already been taken care of in InsetLabel::addToToc().
555                 return;
556         }
557
558         // It seems that this reference does not point to any valid label.
559         broken_ = true;
560         setBroken(broken_);
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));
567 }
568
569
570 void InsetRef::validate(LaTeXFeatures & features) const
571 {
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());
577                 docstring label;
578                 docstring prefix;
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);
583                 if (use_refstyle) {
584                         features.require("refstyle");
585                         if (prefix == "cha")
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);
591                         }
592                 } else {
593                         features.require("prettyref");
594                         // prettyref uses "cha" for chapters, so we provide a kind of
595                         // translation.
596                         if (prefix == "chap")
597                                 features.addPreambleSnippet(from_ascii("\\let\\pr@chap=\\pr@cha"));
598                 }
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");
604 }
605
606 bool InsetRef::forceLTR(OutputParams const & rp) const
607 {
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())
615                 return false;
616         return (getCmdName() != "nameref" || !buffer().masterParams().useNonTeXFonts);
617 }
618
619
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")},
629         { "", "", "" }
630 };
631
632
633 docstring InsetRef::getTOCString() const
634 {
635         docstring const & label = getParam("reference");
636         if (buffer().insetLabel(label))
637                 broken_ = !buffer().activeLabel(label) && active_;
638         else 
639                 broken_ = active_;
640         return tooltip_.empty() ? screenLabel() : tooltip_;
641 }
642
643 } // namespace lyx