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