]> git.lyx.org Git - lyx.git/blob - src/insets/InsetRef.cpp
Tell updateBuffer whether an inset is deleted.
[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 "ParIterator.h"
26 #include "sgml.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)
44 {}
45
46
47 InsetRef::InsetRef(InsetRef const & ir)
48         : InsetCommand(ir), broken_(false)
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         // otherwise not for us
127         if (pstring.empty())
128                 return InsetCommand::doDispatch(cur, cmd);
129
130         bool const isSet = (getParam(pstring) == "true");
131         setParam(pstring, from_ascii(isSet ? "false"  : "true"));
132 }
133
134
135 bool InsetRef::getStatus(Cursor & cur, FuncRequest const & cmd,
136         FuncStatus & status) const
137 {
138         if (cmd.action() != LFUN_INSET_MODIFY)
139                 return InsetCommand::getStatus(cur, cmd, status);
140         if (cmd.getArg(0) != "ref")
141                 return InsetCommand::getStatus(cur, cmd, status);
142
143         string const arg = cmd.getArg(1);
144         string pstring;
145         if (arg == "changetarget")
146                 return true;
147         if (arg == "toggle-plural")
148                 pstring = "plural";
149         else if (arg == "toggle-caps")
150                 pstring = "caps";
151         if (!pstring.empty()) {
152                 status.setEnabled(buffer().params().use_refstyle &&
153                         params().getCmdName() == "formatted");
154                 bool const isSet = (getParam(pstring) == "true");
155                 status.setOnOff(isSet);
156                 return true;
157         }
158         if (arg == "toggle-noprefix") {
159                 status.setEnabled(params().getCmdName() == "labelonly");
160                 bool const isSet = (getParam("noprefix") == "true");
161                 status.setOnOff(isSet);
162                 return true;
163         }
164         // otherwise not for us
165         return InsetCommand::getStatus(cur, cmd, status);
166 }
167
168
169 namespace {
170
171 void capitalize(docstring & s) {
172         char_type t = uppercase(s[0]);
173         s[0] = t;
174 }
175
176 } // namespace
177
178
179 // the ref argument is the label name we are referencing.
180 // we expect ref to be in the form: pfx:suffix.
181 //
182 // if it isn't, then we can't produce a formatted reference,
183 // so we return "\ref" and put ref into label.
184 //
185 // for refstyle, we return "\pfxcmd", and put suffix into
186 // label and pfx into prefix. this is because refstyle expects
187 // the command: \pfxcmd{suffix}.
188 //
189 // for prettyref, we return "\prettyref" and put ref into label
190 // and pfx into prefix. this is because prettyref uses the whole
191 // label, thus: \prettyref{pfx:suffix}.
192 //
193 docstring InsetRef::getFormattedCmd(docstring const & ref,
194         docstring & label, docstring & prefix, docstring const & caps) const
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                 label = ref;
212                 return defcmd;
213         }
214
215         if (!buffer().params().use_refstyle) {
216                 // \prettyref uses the whole label
217                 label = ref;
218                 return prtcmd;
219         }
220
221         // make sure the prefix is legal for a latex command
222         int const len = prefix.size();
223         for (int i = 0; i < len; i++) {
224                 char_type const c = prefix[i];
225                 if (!isAlphaASCII(c)) {
226                         LYXERR0("Prefix `" << prefix << "' is invalid for LaTeX.");
227                         // restore the label
228                         label = ref;
229                         return defcmd;
230                 }
231         }
232         if (caps == "true") {
233                 capitalize(prefix);
234         }
235         return from_ascii("\\") + prefix + from_ascii("ref");
236 }
237
238
239 docstring InsetRef::getEscapedLabel(OutputParams const & rp) const
240 {
241         InsetCommandParams const & p = params();
242         ParamInfo const & pi = p.info();
243         ParamInfo::ParamData const & pd = pi["reference"];
244         return p.prepareCommand(rp, getParam("reference"), pd.handling());
245 }
246
247
248 void InsetRef::latex(otexstream & os, OutputParams const & rp) const
249 {
250         string const & cmd = getCmdName();
251         docstring const & data = getEscapedLabel(rp);
252
253         if (rp.inulemcmd > 0)
254                 os << "\\mbox{";
255
256         if (cmd == "eqref" && buffer().params().use_refstyle) {
257                 // we advertise this as printing "(n)", so we'll do that, at least
258                 // for refstyle, since refstlye's own \eqref prints, by default,
259                 // "equation n". if one wants \eqref, one can get it by using a
260                 // formatted label in this case.
261                 os << '(' << from_ascii("\\ref{") << data << from_ascii("})");
262         }
263         else if (cmd == "formatted") {
264                 docstring label;
265                 docstring prefix;
266                 docstring const fcmd =
267                         getFormattedCmd(data, label, prefix, getParam("caps"));
268                 os << fcmd;
269                 if (buffer().params().use_refstyle && getParam("plural") == "true")
270                     os << "[s]";
271                 os << '{' << label << '}';
272         }
273         else if (cmd == "labelonly") {
274                 docstring const & ref = getParam("reference");
275                 if (getParam("noprefix") != "true")
276                         os << ref;
277                 else {
278                         docstring prefix;
279                         docstring suffix = split(ref, prefix, ':');
280                         if (suffix.empty()) {
281                     LYXERR0("Label `" << ref << "' contains no `:' separator.");
282                                 os << ref;
283                         } else {
284                                 os << suffix;
285                         }
286                 }
287         }
288         else {
289                 // We don't want to output p_["name"], since that is only used
290                 // in docbook. So we construct new params, without it, and use that.
291                 InsetCommandParams p(REF_CODE, cmd);
292                 docstring const ref = getParam("reference");
293                 p["reference"] = ref;
294                 os << p.getCommand(rp);
295         }
296
297         if (rp.inulemcmd > 0)
298                 os << "}";
299 }
300
301
302 int InsetRef::plaintext(odocstringstream & os,
303         OutputParams const &, size_t) const
304 {
305         docstring const str = getParam("reference");
306         os << '[' << str << ']';
307         return 2 + str.size();
308 }
309
310
311 int InsetRef::docbook(odocstream & os, OutputParams const & runparams) const
312 {
313         docstring const & name = getParam("name");
314         if (name.empty()) {
315                 if (runparams.flavor == OutputParams::XML) {
316                         os << "<xref linkend=\""
317                            << sgml::cleanID(buffer(), runparams, getParam("reference"))
318                            << "\" />";
319                 } else {
320                         os << "<xref linkend=\""
321                            << sgml::cleanID(buffer(), runparams, getParam("reference"))
322                            << "\">";
323                 }
324         } else {
325                 os << "<link linkend=\""
326                    << sgml::cleanID(buffer(), runparams, getParam("reference"))
327                    << "\">"
328                    << getParam("name")
329                    << "</link>";
330         }
331
332         return 0;
333 }
334
335
336 docstring InsetRef::xhtml(XHTMLStream & xs, OutputParams const & op) const
337 {
338         docstring const & ref = getParam("reference");
339         InsetLabel const * il = buffer().insetLabel(ref, true);
340         string const & cmd = params().getCmdName();
341         docstring display_string;
342
343         if (il && !il->counterValue().empty()) {
344                 // Try to construct a label from the InsetLabel we reference.
345                 docstring const & value = il->counterValue();
346                 if (cmd == "ref")
347                         display_string = value;
348                 else if (cmd == "vref")
349                         // normally, would be "ref on page #", but we have no pages
350                         display_string = value;
351                 else if (cmd == "pageref" || cmd == "vpageref")
352                         // normally would be "on page #", but we have no pages.
353                         display_string = translateIfPossible(from_ascii("elsewhere"),
354                                 op.local_font->language()->lang());
355                 else if (cmd == "eqref")
356                         display_string = '(' + value + ')';
357                 else if (cmd == "formatted") {
358                         display_string = il->prettyCounter();
359                         if (buffer().params().use_refstyle && getParam("caps") == "true")
360                                 capitalize(display_string);
361                         // it is hard to see what to do about plurals...
362                 }
363                 else if (cmd == "nameref")
364                         // FIXME We don't really have the ability to handle these
365                         // properly in XHTML output yet (bug #8599).
366                         // It might not be that hard to do. We have the InsetLabel,
367                         // and we can presumably find its paragraph using the TOC.
368                         // But the label might be referencing a section, yet not be
369                         // in that section. So this is not trivial.
370                         display_string = il->prettyCounter();
371         } else
372                         display_string = ref;
373
374         // FIXME What we'd really like to do is to be able to output some
375         // appropriate sort of text here. But to do that, we need to associate
376         // some sort of counter with the label, and we don't have that yet.
377         docstring const attr = "href=\"#" + html::cleanAttr(ref) + '"';
378         xs << html::StartTag("a", to_utf8(attr));
379         xs << display_string;
380         xs << html::EndTag("a");
381         return docstring();
382 }
383
384
385 void InsetRef::toString(odocstream & os) const
386 {
387         odocstringstream ods;
388         plaintext(ods, OutputParams(0));
389         os << ods.str();
390 }
391
392
393 void InsetRef::forOutliner(docstring & os, size_t const, bool const) const
394 {
395         // There's no need for details in the TOC, and a long label
396         // will just get in the way.
397         os += '#';
398 }
399
400
401 void InsetRef::updateBuffer(ParIterator const & it, UpdateType, bool const /*deleted*/)
402 {
403         docstring const & ref = getParam("reference");
404         // register this inset into the buffer reference cache.
405         buffer().addReference(ref, this, it);
406
407         docstring label;
408         string const & cmd = getCmdName();
409         for (int i = 0; !types[i].latex_name.empty(); ++i) {
410                 if (cmd == types[i].latex_name) {
411                         label = _(types[i].short_gui_name);
412                         break;
413                 }
414         }
415
416         if (cmd != "labelonly")
417                 label += ref;
418         else {
419                 if (getParam("noprefix") != "true")
420                         label += ref;
421                 else {
422                         docstring prefix;
423                         docstring suffix = split(ref, prefix, ':');
424                         if (suffix.empty()) {
425                                 label += ref;
426                         } else {
427                                 label += suffix;
428                         }
429                 }
430         }
431
432         if (!buffer().params().isLatex() && !getParam("name").empty()) {
433                 label += "||";
434                 label += getParam("name");
435         }
436
437         unsigned int const maxLabelChars = 24;
438         if (label.size() > maxLabelChars) {
439                 tooltip_ = label;
440                 support::truncateWithEllipsis(label, maxLabelChars);
441         } else
442                 tooltip_ = from_ascii("");
443
444         screen_label_ = label;
445         broken_ = false;
446 }
447
448
449 docstring InsetRef::screenLabel() const
450 {
451         return (broken_ ? _("BROKEN: ") : docstring()) + screen_label_;
452 }
453
454
455 void InsetRef::addToToc(DocIterator const & cpit, bool output_active,
456                                                 UpdateType, TocBackend & backend) const
457 {
458         docstring const & label = getParam("reference");
459         if (buffer().insetLabel(label)) {
460                 broken_ = !buffer().activeLabel(label);
461                 // This InsetRef has already been taken care of in InsetLabel::addToToc().
462                 return;
463         }
464
465         // It seems that this reference does not point to any valid label.
466
467         broken_ = true;
468         shared_ptr<Toc> toc = backend.toc("label");
469         toc->push_back(TocItem(cpit, 0, screenLabel(), output_active));
470 }
471
472
473 void InsetRef::validate(LaTeXFeatures & features) const
474 {
475         string const cmd = getCmdName();
476         if (cmd == "vref" || cmd == "vpageref")
477                 features.require("varioref");
478         else if (cmd == "formatted") {
479                 docstring const data = getEscapedLabel(features.runparams());
480                 docstring label;
481                 docstring prefix;
482                 docstring const fcmd =
483                         getFormattedCmd(data, label, prefix, getParam("caps"));
484                 if (buffer().params().use_refstyle) {
485                         features.require("refstyle");
486                         if (prefix == "cha")
487                                 features.addPreambleSnippet(from_ascii("\\let\\charef=\\chapref"));
488                         else if (!prefix.empty()) {
489                                 docstring lcmd = "\\AtBeginDocument{\\providecommand" +
490                                                 fcmd + "[1]{\\ref{" + prefix + ":#1}}}";
491                                 features.addPreambleSnippet(lcmd);
492                         }
493                 } else {
494                         features.require("prettyref");
495                         // prettyref uses "cha" for chapters, so we provide a kind of
496                         // translation.
497                         if (prefix == "chap")
498                                 features.addPreambleSnippet(from_ascii("\\let\\pr@chap=\\pr@cha"));
499                 }
500         } else if (cmd == "eqref" && !buffer().params().use_refstyle)
501                 // with refstyle, we simply output "(\ref{label})"
502                 features.require("amsmath");
503         else if (cmd == "nameref")
504                 features.require("nameref");
505 }
506
507 bool InsetRef::forceLTR(OutputParams const & rp) const
508 {
509         // We force LTR for references. However,
510         // * Namerefs are output in the scripts direction
511         //   at least with fontspec/bidi and luabidi, though (see #11518).
512         // * Parentheses are automatically swapped with XeTeX/bidi 
513         //   [not with LuaTeX/luabidi] (see #11626).
514         // FIXME: Re-Audit all other RTL cases.
515         if (rp.useBidiPackage())
516                 return false;
517         return (getCmdName() != "nameref" || !buffer().masterParams().useNonTeXFonts);
518 }
519
520
521 InsetRef::type_info const InsetRef::types[] = {
522         { "ref",       N_("Standard"),              N_("Ref: ")},
523         { "eqref",     N_("Equation"),              N_("EqRef: ")},
524         { "pageref",   N_("Page Number"),           N_("Page: ")},
525         { "vpageref",  N_("Textual Page Number"),   N_("TextPage: ")},
526         { "vref",      N_("Standard+Textual Page"), N_("Ref+Text: ")},
527         { "nameref",   N_("Reference to Name"),     N_("NameRef: ")},
528         { "formatted", N_("Formatted"),             N_("Format: ")},
529         { "labelonly", N_("Label Only"),            N_("Label: ")},
530         { "", "", "" }
531 };
532
533
534 docstring InsetRef::getTOCString() const
535 {
536         return tooltip_.empty() ? screenLabel() : tooltip_;
537 }
538
539 } // namespace lyx