]> git.lyx.org Git - lyx.git/blob - src/insets/InsetRef.cpp
Add empty line after last \bibitem in bibliography (#12041)
[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 "xml.h"
27 #include "texstream.h"
28 #include "TocBackend.h"
29
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"
35
36 using namespace lyx::support;
37 using namespace std;
38
39 namespace lyx {
40
41
42 InsetRef::InsetRef(Buffer * buf, InsetCommandParams const & p)
43         : InsetCommand(buf, p), broken_(false), active_(true)
44 {}
45
46
47 InsetRef::InsetRef(InsetRef const & ir)
48         : InsetCommand(ir), broken_(false), active_(true)
49 {}
50
51
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.
55         return s == "ref"
56                 || s == "pageref"
57                 || s == "vref"
58                 || s == "vpageref"
59                 || s == "formatted"
60                 || s == "prettyref" // for InsetMathRef FIXME
61                 || s == "eqref"
62                 || s == "nameref"
63                 || s == "labelonly";
64 }
65
66
67 ParamInfo const & InsetRef::findInfo(string const & /* cmdName */)
68 {
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);
77         }
78         return param_info_;
79 }
80
81
82 docstring InsetRef::layoutName() const
83 {
84         return from_ascii("Ref");
85 }
86
87
88 void InsetRef::changeTarget(docstring const & new_label)
89 {
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));
98         } else
99                 setParam("reference", new_label);
100 }
101
102
103
104 void InsetRef::doDispatch(Cursor & cur, FuncRequest & cmd)
105 {
106         string const inset = cmd.getArg(0);
107         string const arg   = cmd.getArg(1);
108         string pstring;
109         if (cmd.action() == LFUN_INSET_MODIFY && inset == "ref") {
110                 if (arg == "toggle-plural")
111                         pstring = "plural";
112                 else if (arg == "toggle-caps")
113                         pstring = "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();
123                         return;
124                 }
125         }
126
127         // Ctrl + click: go to label
128         if (cmd.action() == LFUN_MOUSE_RELEASE && cmd.modifier() == ControlModifier) {
129                         lyx::dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
130                         lyx::dispatch(FuncRequest(LFUN_LABEL_GOTO, getParam("reference")));
131                         return;
132                 }
133
134         // otherwise not for us
135         if (pstring.empty())
136                 return InsetCommand::doDispatch(cur, cmd);
137
138         bool const isSet = (getParam(pstring) == "true");
139         setParam(pstring, from_ascii(isSet ? "false"  : "true"));
140 }
141
142
143 bool InsetRef::getStatus(Cursor & cur, FuncRequest const & cmd,
144         FuncStatus & status) const
145 {
146         if (cmd.action() != LFUN_INSET_MODIFY)
147                 return InsetCommand::getStatus(cur, cmd, status);
148         if (cmd.getArg(0) != "ref")
149                 return InsetCommand::getStatus(cur, cmd, status);
150
151         string const arg = cmd.getArg(1);
152         string pstring;
153         if (arg == "changetarget")
154                 return true;
155         if (arg == "toggle-plural")
156                 pstring = "plural";
157         else if (arg == "toggle-caps")
158                 pstring = "caps";
159         if (!pstring.empty()) {
160                 status.setEnabled(buffer().params().use_refstyle &&
161                         params().getCmdName() == "formatted");
162                 bool const isSet = (getParam(pstring) == "true");
163                 status.setOnOff(isSet);
164                 return true;
165         }
166         if (arg == "toggle-noprefix") {
167                 status.setEnabled(params().getCmdName() == "labelonly");
168                 bool const isSet = (getParam("noprefix") == "true");
169                 status.setOnOff(isSet);
170                 return true;
171         }
172         // otherwise not for us
173         return InsetCommand::getStatus(cur, cmd, status);
174 }
175
176
177 namespace {
178
179 void capitalize(docstring & s) {
180         char_type t = uppercase(s[0]);
181         s[0] = t;
182 }
183
184 } // namespace
185
186
187 // the ref argument is the label name we are referencing.
188 // we expect ref to be in the form: pfx:suffix.
189 //
190 // if it isn't, then we can't produce a formatted reference,
191 // so we return "\ref" and put ref into label.
192 //
193 // for refstyle, we return "\pfxcmd", and put suffix into
194 // label and pfx into prefix. this is because refstyle expects
195 // the command: \pfxcmd{suffix}.
196 //
197 // for prettyref, we return "\prettyref" and put ref into label
198 // and pfx into prefix. this is because prettyref uses the whole
199 // label, thus: \prettyref{pfx:suffix}.
200 //
201 docstring InsetRef::getFormattedCmd(docstring const & ref,
202         docstring & label, docstring & prefix, docstring const & caps) const
203 {
204         static docstring const defcmd = from_ascii("\\ref");
205         static docstring const prtcmd = from_ascii("\\prettyref");
206
207         label = split(ref, prefix, ':');
208
209         // we have to have xxx:xxxxx...
210         if (label.empty()) {
211                 LYXERR0("Label `" << ref << "' contains no `:' separator.");
212                 label = ref;
213                 prefix = from_ascii("");
214                 return defcmd;
215         }
216
217         if (prefix.empty()) {
218                 // we have ":xxxx"
219                 label = ref;
220                 return defcmd;
221         }
222
223         if (!buffer().params().use_refstyle) {
224                 // \prettyref uses the whole label
225                 label = ref;
226                 return prtcmd;
227         }
228
229         // make sure the prefix is legal for a latex command
230         size_t const len = prefix.size();
231         for (size_t i = 0; i < len; i++) {
232                 char_type const c = prefix[i];
233                 if (!isAlphaASCII(c)) {
234                         LYXERR0("Prefix `" << prefix << "' is invalid for LaTeX.");
235                         // restore the label
236                         label = ref;
237                         return defcmd;
238                 }
239         }
240         if (caps == "true") {
241                 capitalize(prefix);
242         }
243         return from_ascii("\\") + prefix + from_ascii("ref");
244 }
245
246
247 docstring InsetRef::getEscapedLabel(OutputParams const & rp) const
248 {
249         InsetCommandParams const & p = params();
250         ParamInfo const & pi = p.info();
251         ParamInfo::ParamData const & pd = pi["reference"];
252         return p.prepareCommand(rp, getParam("reference"), pd.handling());
253 }
254
255
256 void InsetRef::latex(otexstream & os, OutputParams const & rp) const
257 {
258         string const & cmd = getCmdName();
259         docstring const & data = getEscapedLabel(rp);
260
261         if (rp.inulemcmd > 0)
262                 os << "\\mbox{";
263
264         if (cmd == "eqref" && buffer().params().use_refstyle) {
265                 // we advertise this as printing "(n)", so we'll do that, at least
266                 // for refstyle, since refstlye's own \eqref prints, by default,
267                 // "equation n". if one wants \eqref, one can get it by using a
268                 // formatted label in this case.
269                 os << '(' << from_ascii("\\ref{") << data << from_ascii("})");
270         }
271         else if (cmd == "formatted") {
272                 docstring label;
273                 docstring prefix;
274                 docstring const fcmd =
275                         getFormattedCmd(data, label, prefix, getParam("caps"));
276                 os << fcmd;
277                 if (buffer().params().use_refstyle && getParam("plural") == "true")
278                     os << "[s]";
279                 os << '{' << label << '}';
280         }
281         else if (cmd == "labelonly") {
282                 docstring const & ref = getParam("reference");
283                 if (getParam("noprefix") != "true")
284                         os << ref;
285                 else {
286                         docstring prefix;
287                         docstring suffix = split(ref, prefix, ':');
288                         if (suffix.empty()) {
289                     LYXERR0("Label `" << ref << "' contains no `:' separator.");
290                                 os << ref;
291                         } else {
292                                 os << suffix;
293                         }
294                 }
295         }
296         else {
297                 InsetCommandParams p(REF_CODE, cmd);
298                 docstring const ref = getParam("reference");
299                 p["reference"] = ref;
300                 os << p.getCommand(rp);
301         }
302
303         if (rp.inulemcmd > 0)
304                 os << "}";
305 }
306
307
308 int InsetRef::plaintext(odocstringstream & os,
309         OutputParams const &, size_t) const
310 {
311         docstring const str = getParam("reference");
312         os << '[' << str << ']';
313         return 2 + int(str.size());
314 }
315
316
317 void InsetRef::docbook(XMLStream & xs, OutputParams const &) const
318 {
319         docstring const & ref = getParam("reference");
320         InsetLabel const * il = buffer().insetLabel(ref, true);
321         string const & cmd = params().getCmdName();
322         docstring linkend = xml::cleanID(ref);
323
324         // A name is provided, LyX will provide it. This is supposed to be a very rare case.
325         // Link with linkend, as is it within the document (not outside, in which case xlink:href is better suited).
326         docstring const & name = getParam("name");
327         if (!name.empty()) {
328                 docstring attr = from_utf8("linkend=\"") + linkend + from_utf8("\"");
329
330                 xs << xml::StartTag("link", to_utf8(attr));
331                 xs << name;
332                 xs << xml::EndTag("link");
333                 return;
334         }
335
336         // The DocBook processor will generate the name when required.
337         docstring display_before;
338         docstring display_after;
339         docstring role;
340
341         if (il && !il->counterValue().empty()) {
342                 // Try to construct a label from the InsetLabel we reference.
343                 if (cmd == "vref" || cmd == "pageref" || cmd == "vpageref" || cmd == "nameref" || cmd == "formatted") {
344                         // "ref on page #", "on page #", etc. The DocBook processor deals with generating the right text,
345                         // including in the right language.
346                         role = from_ascii(cmd);
347
348                         if (cmd == "formatted") {
349                                 // A formatted reference may have many parameters. Generate all of them as roles, the only
350                                 // way arbitrary parameters can be passed into DocBook.
351                                 if (buffer().params().use_refstyle && getParam("caps") == "true")
352                                         role += " refstyle-caps";
353                                 if (buffer().params().use_refstyle && getParam("plural") == "true")
354                                         role += " refstyle-plural";
355                         }
356                 } else if (cmd == "eqref") {
357                         display_before = from_ascii("(");
358                         display_after = from_ascii(")");
359                 }
360                 // TODO: what about labelonly? I don't get how this is supposed to work...
361         }
362
363         // No name, ask DocBook to generate one.
364         docstring attr = from_utf8("linkend=\"") + xml::cleanID(ref) + from_utf8("\"");
365         if (!role.empty())
366                 attr += " role=\"" + role + "\"";
367         xs << display_before;
368         xs << xml::CompTag("xref", to_utf8(attr));
369         xs << display_after;
370 }
371
372
373 docstring InsetRef::xhtml(XMLStream & xs, OutputParams const & op) const
374 {
375         docstring const & ref = getParam("reference");
376         InsetLabel const * il = buffer().insetLabel(ref, true);
377         string const & cmd = params().getCmdName();
378         docstring display_string;
379
380         if (il && !il->counterValue().empty()) {
381                 // Try to construct a label from the InsetLabel we reference.
382                 docstring const & value = il->counterValue();
383                 if (cmd == "ref")
384                         display_string = value;
385                 else if (cmd == "vref")
386                         // normally, would be "ref on page #", but we have no pages
387                         display_string = value;
388                 else if (cmd == "pageref" || cmd == "vpageref")
389                         // normally would be "on page #", but we have no pages.
390                         display_string = translateIfPossible(from_ascii("elsewhere"),
391                                 op.local_font->language()->lang());
392                 else if (cmd == "eqref")
393                         display_string = '(' + value + ')';
394                 else if (cmd == "formatted") {
395                         display_string = il->prettyCounter();
396                         if (buffer().params().use_refstyle && getParam("caps") == "true")
397                                 capitalize(display_string);
398                         // it is hard to see what to do about plurals...
399                 }
400                 else if (cmd == "nameref")
401                         // FIXME We don't really have the ability to handle these
402                         // properly in XHTML output yet (bug #8599).
403                         // It might not be that hard to do. We have the InsetLabel,
404                         // and we can presumably find its paragraph using the TOC.
405                         // But the label might be referencing a section, yet not be
406                         // in that section. So this is not trivial.
407                         display_string = il->prettyCounter();
408         } else
409                         display_string = ref;
410
411         // FIXME What we'd really like to do is to be able to output some
412         // appropriate sort of text here. But to do that, we need to associate
413         // some sort of counter with the label, and we don't have that yet.
414         docstring const attr = "href=\"#" + xml::cleanAttr(ref) + '"';
415         xs << xml::StartTag("a", to_utf8(attr));
416         xs << display_string;
417         xs << xml::EndTag("a");
418         return docstring();
419 }
420
421
422 void InsetRef::toString(odocstream & os) const
423 {
424         odocstringstream ods;
425         plaintext(ods, OutputParams(nullptr));
426         os << ods.str();
427 }
428
429
430 void InsetRef::forOutliner(docstring & os, size_t const, bool const) const
431 {
432         // There's no need for details in the TOC, and a long label
433         // will just get in the way.
434         os += '#';
435 }
436
437
438 void InsetRef::updateBuffer(ParIterator const & it, UpdateType, bool const /*deleted*/)
439 {
440         docstring const & ref = getParam("reference");
441
442         // Check if this one is active (i.e., neither deleted with change-tracking
443         // nor in an inset that does not produce output, such as notes or inactive branches)
444         Paragraph const & para = it.paragraph();
445         active_ = !para.isDeleted(it.pos()) && para.inInset().producesOutput();
446         // If not, check whether we are in a deleted/non-outputting inset
447         if (active_) {
448                 for (size_type sl = 0 ; sl < it.depth() ; ++sl) {
449                         Paragraph const & outer_par = it[sl].paragraph();
450                         if (outer_par.isDeleted(it[sl].pos())
451                             || !outer_par.inInset().producesOutput()) {
452                                 active_ = false;
453                                 break;
454                         }
455                 }
456         }
457
458         // register this inset into the buffer reference cache.
459         buffer().addReference(ref, this, it);
460
461         docstring label;
462         string const & cmd = getCmdName();
463         for (int i = 0; !types[i].latex_name.empty(); ++i) {
464                 if (cmd == types[i].latex_name) {
465                         label = _(types[i].short_gui_name);
466                         break;
467                 }
468         }
469
470         if (cmd != "labelonly")
471                 label += ref;
472         else {
473                 if (getParam("noprefix") != "true")
474                         label += ref;
475                 else {
476                         docstring prefix;
477                         docstring suffix = split(ref, prefix, ':');
478                         if (suffix.empty()) {
479                                 label += ref;
480                         } else {
481                                 label += suffix;
482                         }
483                 }
484         }
485
486         if (!buffer().params().isLatex() && !getParam("name").empty()) {
487                 label += "||";
488                 label += getParam("name");
489         }
490
491         unsigned int const maxLabelChars = 24;
492         if (label.size() > maxLabelChars) {
493                 tooltip_ = label;
494                 support::truncateWithEllipsis(label, maxLabelChars);
495         } else
496                 tooltip_ = from_ascii("");
497
498         screen_label_ = label;
499         broken_ = false;
500         setBroken(broken_);
501 }
502
503
504 docstring InsetRef::screenLabel() const
505 {
506         return (broken_ ? _("BROKEN: ") : docstring()) + screen_label_;
507 }
508
509
510 void InsetRef::addToToc(DocIterator const & cpit, bool output_active,
511                         UpdateType, TocBackend & backend) const
512 {
513         active_ = output_active;
514         docstring const & label = getParam("reference");
515         if (buffer().insetLabel(label)) {
516                 broken_ = !buffer().activeLabel(label) && active_;
517                 setBroken(broken_);
518                 if (broken_ && output_active) {
519                         shared_ptr<Toc> toc2 = backend.toc("brokenrefs");
520                         toc2->push_back(TocItem(cpit, 0, screenLabel(), output_active));
521                 }
522                 // This InsetRef has already been taken care of in InsetLabel::addToToc().
523                 return;
524         }
525
526         // It seems that this reference does not point to any valid label.
527         broken_ = true;
528         setBroken(broken_);
529         shared_ptr<Toc> toc = backend.toc("label");
530         toc->push_back(TocItem(cpit, 0, screenLabel(), output_active));
531         shared_ptr<Toc> toc2 = backend.toc("brokenrefs");
532         toc2->push_back(TocItem(cpit, 0, screenLabel(), output_active));
533 }
534
535
536 void InsetRef::validate(LaTeXFeatures & features) const
537 {
538         string const & cmd = getCmdName();
539         if (cmd == "vref" || cmd == "vpageref")
540                 features.require("varioref");
541         else if (cmd == "formatted") {
542                 docstring const data = getEscapedLabel(features.runparams());
543                 docstring label;
544                 docstring prefix;
545                 docstring const fcmd =
546                         getFormattedCmd(data, label, prefix, getParam("caps"));
547                 if (buffer().params().use_refstyle) {
548                         features.require("refstyle");
549                         if (prefix == "cha")
550                                 features.addPreambleSnippet(from_ascii("\\let\\charef=\\chapref"));
551                         else if (!prefix.empty()) {
552                                 docstring lcmd = "\\AtBeginDocument{\\providecommand" +
553                                                 fcmd + "[1]{\\ref{" + prefix + ":#1}}}";
554                                 features.addPreambleSnippet(lcmd);
555                         }
556                 } else {
557                         features.require("prettyref");
558                         // prettyref uses "cha" for chapters, so we provide a kind of
559                         // translation.
560                         if (prefix == "chap")
561                                 features.addPreambleSnippet(from_ascii("\\let\\pr@chap=\\pr@cha"));
562                 }
563         } else if (cmd == "eqref" && !buffer().params().use_refstyle)
564                 // with refstyle, we simply output "(\ref{label})"
565                 features.require("amsmath");
566         else if (cmd == "nameref")
567                 features.require("nameref");
568 }
569
570 bool InsetRef::forceLTR(OutputParams const & rp) const
571 {
572         // We force LTR for references. However,
573         // * Namerefs are output in the scripts direction
574         //   at least with fontspec/bidi and luabidi, though (see #11518).
575         // * Parentheses are automatically swapped with XeTeX/bidi 
576         //   [not with LuaTeX/luabidi] (see #11626).
577         // FIXME: Re-Audit all other RTL cases.
578         if (rp.useBidiPackage())
579                 return false;
580         return (getCmdName() != "nameref" || !buffer().masterParams().useNonTeXFonts);
581 }
582
583
584 InsetRef::type_info const InsetRef::types[] = {
585         { "ref",       N_("Standard"),              N_("Ref: ")},
586         { "eqref",     N_("Equation"),              N_("EqRef: ")},
587         { "pageref",   N_("Page Number"),           N_("Page: ")},
588         { "vpageref",  N_("Textual Page Number"),   N_("TextPage: ")},
589         { "vref",      N_("Standard+Textual Page"), N_("Ref+Text: ")},
590         { "nameref",   N_("Reference to Name"),     N_("NameRef: ")},
591         { "formatted", N_("Formatted"),             N_("Format: ")},
592         { "labelonly", N_("Label Only"),            N_("Label: ")},
593         { "", "", "" }
594 };
595
596
597 docstring InsetRef::getTOCString() const
598 {
599         docstring const & label = getParam("reference");
600         if (buffer().insetLabel(label))
601                 broken_ = !buffer().activeLabel(label) && active_;
602         else 
603                 broken_ = active_;
604         return tooltip_.empty() ? screenLabel() : tooltip_;
605 }
606
607 } // namespace lyx