]> git.lyx.org Git - lyx.git/blob - src/insets/InsetRef.cpp
Amend 207eaeee9071cb
[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().masterParams().pdfoptions().use_hyperref;
264
265         if (rp.inulemcmd > 0)
266                 os << "\\mbox{";
267
268         if (buffer().masterParams().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().masterParams().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::displayString(docstring const & ref, string const & cmd,
386                 string const & language) const
387
388 {
389         InsetLabel const * il = buffer().insetLabel(ref, true);
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 =
403                                 translateIfPossible(from_ascii("elsewhere"), language);
404                 } else if (cmd == "eqref")
405                         display_string = '(' + value + ')';
406                 else if (cmd == "formatted") {
407                         display_string = il->formattedCounter();
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         return display_string;
423 }
424
425
426 docstring InsetRef::xhtml(XMLStream & xs, OutputParams const & op) const
427         {
428         docstring const & ref = getParam("reference");
429         string const & cmd = params().getCmdName();
430         // FIXME What we'd really like to do is to be able to output some
431         // appropriate sort of text here. But to do that, we need to associate
432         // some sort of counter with the label, and we don't have that yet.
433         docstring const attr = "href=\"#" + xml::cleanAttr(ref) + '"';
434         xs << xml::StartTag("a", to_utf8(attr));
435         xs << displayString(ref, cmd, getLocalOrDefaultLang(op)->lang());
436         xs << xml::EndTag("a");
437         return docstring();
438 }
439
440
441 void InsetRef::toString(odocstream & os) const
442 {
443         odocstringstream ods;
444         plaintext(ods, OutputParams(nullptr));
445         os << ods.str();
446 }
447
448
449 void InsetRef::forOutliner(docstring & os, size_t const, bool const) const
450 {
451         // It's hard to know what to do here. Should we show XREF in the TOC?
452         // Or should we just show that there is one? For now, we do the former.
453         odocstringstream ods;
454         plaintext(ods, OutputParams(nullptr));
455         os += ods.str();
456 }
457
458
459 void InsetRef::updateBuffer(ParIterator const & it, UpdateType, bool const /*deleted*/)
460 {
461         docstring const & ref = getParam("reference");
462
463         // Check if this one is active (i.e., neither deleted with change-tracking
464         // nor in an inset that does not produce output, such as notes or inactive branches)
465         Paragraph const & para = it.paragraph();
466         active_ = !para.isDeleted(it.pos()) && para.inInset().producesOutput();
467         // If not, check whether we are in a deleted/non-outputting inset
468         if (active_) {
469                 for (size_type sl = 0 ; sl < it.depth() ; ++sl) {
470                         Paragraph const & outer_par = it[sl].paragraph();
471                         if (outer_par.isDeleted(it[sl].pos())
472                             || !outer_par.inInset().producesOutput()) {
473                                 active_ = false;
474                                 break;
475                         }
476                 }
477         }
478
479         // register this inset into the buffer reference cache.
480         buffer().addReference(ref, this, it);
481
482         docstring label;
483         string const & cmd = getCmdName();
484         for (int i = 0; !types[i].latex_name.empty(); ++i) {
485                 if (cmd == types[i].latex_name) {
486                         label = _(types[i].short_gui_name);
487                         // indicate no hyperlink (starred)
488                         if (cmd != "formatted" && cmd != "labelonly") {
489                                 bool const isNoLink = getParam("nolink") == "true";
490                                 if (isNoLink)
491                                         label += from_ascii("*");
492                         }
493                         // indicate plural and caps
494                         if (cmd == "formatted") {
495                                 bool const isPlural = getParam("plural") == "true";
496                                 bool const isCaps = getParam("caps") == "true";
497                                 if (isCaps) {
498                                         // up arrow (shift key) symbol
499                                         label += docstring(1, char_type(0x21E7));
500                                 }
501                                 if (isPlural)
502                                         label += from_ascii("+");
503                         }
504                         label += from_ascii(": ");
505                         break;
506                 }
507         }
508
509         if (cmd != "labelonly")
510                 label += ref;
511         else {
512                 if (getParam("noprefix") != "true")
513                         label += ref;
514                 else {
515                         docstring prefix;
516                         docstring suffix = split(ref, prefix, ':');
517                         if (suffix.empty()) {
518                                 label += ref;
519                         } else {
520                                 label += suffix;
521                         }
522                 }
523         }
524
525         if (!buffer().params().isLatex() && !getParam("name").empty()) {
526                 label += "||";
527                 label += getParam("name");
528         }
529
530         bool const use_formatted_ref = buffer().params().use_formatted_ref;
531         unsigned int const maxLabelChars = 24;
532         // Show label in tooltip when formatted references are shown in the work
533         // area or it is too long
534         if (use_formatted_ref || label.size() > maxLabelChars) {
535                 tooltip_ = label;
536                 support::truncateWithEllipsis(label, maxLabelChars);
537         } else
538                 tooltip_ = from_ascii("");
539
540         screen_label_ = label;
541         // If use_formatted_ref is active, this will be overwritten in addToToc.
542         // (We can't do it now because it might be a forward-reference
543         // and so the reference might not be in the label cache yet.
544         broken_ = false;
545         setBroken(broken_);
546 }
547
548
549 docstring InsetRef::screenLabel() const
550 {
551         return (broken_ ? _("BROKEN: ") : docstring()) + screen_label_;
552 }
553
554
555 void InsetRef::addToToc(DocIterator const & cpit, bool output_active,
556                         UpdateType, TocBackend & backend) const
557 {
558         active_ = output_active;
559         docstring const & label = getParam("reference");
560         if (buffer().insetLabel(label)) {
561                 broken_ = !buffer().activeLabel(label) && active_;
562                 setBroken(broken_);
563                 if (broken_ && output_active) {
564                         shared_ptr<Toc> toc2 = backend.toc("brokenrefs");
565                         toc2->push_back(TocItem(cpit, 0, screenLabel(), output_active));
566                 }
567
568                 // Code for display of formatted references
569                 bool const use_formatted_ref = buffer().params().use_formatted_ref;
570                 if (use_formatted_ref) {
571                         string const & cmd = getCmdName();
572                         docstring const & ref = getParam("reference");
573                         if (cmd != "pageref" && cmd != "vpageref" && cmd != "vref" &&
574                                         cmd != "labelonly")
575                                 screen_label_ = displayString(ref, cmd);
576                 }
577                 return;
578         }
579         // It seems that this reference does not point to any valid label.
580         broken_ = true;
581         setBroken(broken_);
582         shared_ptr<Toc> toc = backend.toc("label");
583         if (TocBackend::findItem(*toc, 0, label) == toc->end())
584                 toc->push_back(TocItem(cpit, 0, label, output_active, true));
585         toc->push_back(TocItem(cpit, 1, screenLabel(), output_active));
586         shared_ptr<Toc> toc2 = backend.toc("brokenrefs");
587         toc2->push_back(TocItem(cpit, 0, screenLabel(), output_active));
588 }
589
590
591 void InsetRef::validate(LaTeXFeatures & features) const
592 {
593         string const & cmd = getCmdName();
594         if (cmd == "vref" || cmd == "vpageref")
595                 features.require("varioref");
596         else if (cmd == "formatted") {
597                 docstring const data = getEscapedLabel(features.runparams());
598                 docstring label;
599                 docstring prefix;
600                 bool const use_refstyle = buffer().masterParams().use_refstyle;
601                 bool const use_caps   = getParam("caps") == "true";
602                 docstring const fcmd =
603                         getFormattedCmd(data, label, prefix, use_refstyle, use_caps);
604                 if (use_refstyle) {
605                         features.require("refstyle");
606                         if (prefix == "cha")
607                                 features.addPreambleSnippet(from_ascii("\\let\\charef=\\chapref"));
608                         else if (!prefix.empty()) {
609                                 docstring lcmd = "\\AtBeginDocument{\\providecommand" +
610                                                 fcmd + "[1]{\\ref{" + prefix + ":#1}}}";
611                                 features.addPreambleSnippet(lcmd);
612                         }
613                 } else {
614                         features.require("prettyref");
615                         // prettyref uses "cha" for chapters, so we provide a kind of
616                         // translation.
617                         if (prefix == "chap")
618                                 features.addPreambleSnippet(from_ascii("\\let\\pr@chap=\\pr@cha"));
619                 }
620         } else if (cmd == "eqref" && !buffer().params().use_refstyle)
621                 // with refstyle, we simply output "(\ref{label})"
622                 features.require("amsmath");
623         else if (cmd == "nameref")
624                 features.require("nameref");
625 }
626
627 bool InsetRef::forceLTR(OutputParams const & rp) const
628 {
629         // We force LTR for references. However,
630         // * Namerefs are output in the scripts direction
631         //   at least with fontspec/bidi and luabidi, though (see #11518).
632         // * Parentheses are automatically swapped with XeTeX/bidi 
633         //   [not with LuaTeX/luabidi] (see #11626).
634         // FIXME: Re-Audit all other RTL cases.
635         if (buffer().masterParams().useBidiPackage(rp))
636                 return false;
637         return (getCmdName() != "nameref" || !buffer().masterParams().useNonTeXFonts);
638 }
639
640
641 InsetRef::type_info const InsetRef::types[] = {
642         { "ref",       N_("Standard"),              N_("Ref")},
643         { "eqref",     N_("Equation"),              N_("EqRef")},
644         { "pageref",   N_("Page Number"),           N_("Page")},
645         { "vpageref",  N_("Textual Page Number"),   N_("TextPage")},
646         { "vref",      N_("Standard+Textual Page"), N_("Ref+Text")},
647         { "nameref",   N_("Reference to Name"),     N_("NameRef")},
648         { "formatted", N_("Formatted"),             N_("Format")},
649         { "labelonly", N_("Label Only"),            N_("Label")},
650         { "", "", "" }
651 };
652
653
654 docstring InsetRef::getTOCString() const
655 {
656         docstring const & label = getParam("reference");
657         if (buffer().insetLabel(label))
658                 broken_ = !buffer().activeLabel(label) && active_;
659         else 
660                 broken_ = active_;
661         return tooltip_.empty() ? screenLabel() : tooltip_;
662 }
663
664 } // namespace lyx