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