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