]> git.lyx.org Git - features.git/blob - src/insets/InsetRef.cpp
Add a member to TocItem that tells us whether the item in question
[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 "InsetLabel.h"
19 #include "LaTeXFeatures.h"
20 #include "LyX.h"
21 #include "OutputParams.h"
22 #include "output_xhtml.h"
23 #include "ParIterator.h"
24 #include "sgml.h"
25 #include "TocBackend.h"
26
27 #include "support/debug.h"
28 #include "support/docstream.h"
29 #include "support/gettext.h"
30 #include "support/lstrings.h"
31 #include "support/textutils.h"
32
33 using namespace lyx::support;
34 using namespace std;
35
36 namespace lyx {
37
38
39 InsetRef::InsetRef(Buffer * buf, InsetCommandParams const & p)
40         : InsetCommand(buf, p)
41 {}
42
43
44 InsetRef::InsetRef(InsetRef const & ir)
45         : InsetCommand(ir)
46 {}
47
48
49 bool InsetRef::isCompatibleCommand(string const & s) {
50         //FIXME This is likely not the best way to handle this.
51         //But this stuff is hardcoded elsewhere already.
52         return s == "ref" 
53                 || s == "pageref"
54                 || s == "vref" 
55                 || s == "vpageref"
56                 || s == "formatted"
57                 || s == "eqref"
58                 || s == "nameref";
59 }
60
61
62 ParamInfo const & InsetRef::findInfo(string const & /* cmdName */)
63 {
64         static ParamInfo param_info_;
65         if (param_info_.empty()) {
66                 param_info_.add("name", ParamInfo::LATEX_OPTIONAL);
67                 param_info_.add("reference", ParamInfo::LATEX_REQUIRED,
68                                 ParamInfo::HANDLING_ESCAPE);
69         }
70         return param_info_;
71 }
72
73
74 // the ref argument is the label name we are referencing.
75 // we expect ref to be in the form: pfx:suffix.
76 //
77 // if it isn't, then we can't produce a formatted reference, 
78 // so we return "\ref" and put ref into label.
79 //
80 // for refstyle, we return "\pfxcmd", and put suffix into 
81 // label and pfx into prefix. this is because refstyle expects
82 // the command: \pfxcmd{suffix}.
83 // 
84 // for prettyref, we return "\prettyref" and put ref into label
85 // and pfx into prefix. this is because prettyref uses the whole
86 // label, thus: \prettyref{pfx:suffix}.
87 //
88 docstring InsetRef::getFormattedCmd(docstring const & ref, 
89         docstring & label, docstring & prefix) const
90 {
91         static docstring const defcmd = from_ascii("\\ref");
92         static docstring const prtcmd = from_ascii("\\prettyref");
93         
94         label = split(ref, prefix, ':');
95
96         // we have to have xxx:xxxxx...
97         if (label.empty()) {
98                 LYXERR0("Label `" << ref << "' contains no prefix.");
99                 label = ref;
100                 prefix = from_ascii("");
101                 return defcmd;
102         }
103
104         if (prefix.empty()) {
105                 // we have ":xxxx"
106                 label = ref;
107                 return defcmd;
108         }
109         
110         if (!buffer().params().use_refstyle) {
111                 // \prettyref uses the whole label
112                 label = ref;
113                 return prtcmd;
114         }
115
116         // make sure the prefix is legal for a latex command
117         int const len = prefix.size();
118         for (int i = 0; i < len; i++) {
119                 char_type const c = prefix[i];
120                 if (!isAlphaASCII(c)) {
121                         LYXERR0("Prefix `" << prefix << "' is invalid for LaTeX.");
122                         // restore the label
123                         label = ref;
124                         return defcmd;
125                 }
126         }
127         return from_ascii("\\") + prefix + from_ascii("ref");
128 }
129
130
131 docstring InsetRef::getEscapedLabel(OutputParams const & rp) const
132 {
133         InsetCommandParams const & p = params();
134         ParamInfo const & pi = p.info();
135         ParamInfo::ParamData const & pd = pi["reference"];
136         return p.prepareCommand(rp, getParam("reference"), pd.handling());              
137 }
138
139
140 void InsetRef::latex(otexstream & os, OutputParams const & rp) const
141 {
142         string const cmd = getCmdName();
143         docstring const data = getEscapedLabel(rp);
144
145         if (rp.inulemcmd)
146                 os << "\\mbox{";
147
148         if (cmd == "eqref" && buffer().params().use_refstyle) {
149                 // we advertise this as printing "(n)", so we'll do that, at least
150                 // for refstyle, since refstlye's own \eqref prints, by default,
151                 // "equation n". if one wants \eqref, one can get it by using a
152                 // formatted label in this case.
153                 os << '(' << from_ascii("\\ref{") << data << from_ascii("})");
154         } 
155         else if (cmd == "formatted") {
156                 docstring label;
157                 docstring prefix;
158                 docstring const fcmd = getFormattedCmd(data, label, prefix);
159                 os << fcmd << '{' << label << '}';
160         }
161         else {
162                 // We don't want to output p_["name"], since that is only used 
163                 // in docbook. So we construct new params, without it, and use that.
164                 InsetCommandParams p(REF_CODE, cmd);
165                 docstring const ref = getParam("reference");
166                 p["reference"] = ref;
167                 os << p.getCommand(rp);
168         }
169
170         if (rp.inulemcmd)
171                 os << "}";
172 }
173
174
175 int InsetRef::plaintext(odocstringstream & os,
176         OutputParams const &, size_t) const
177 {
178         docstring const str = getParam("reference");
179         os << '[' << str << ']';
180         return 2 + str.size();
181 }
182
183
184 int InsetRef::docbook(odocstream & os, OutputParams const & runparams) const
185 {
186         docstring const & name = getParam("name");
187         if (name.empty()) {
188                 if (runparams.flavor == OutputParams::XML) {
189                         os << "<xref linkend=\""
190                            << sgml::cleanID(buffer(), runparams, getParam("reference"))
191                            << "\" />";
192                 } else {
193                         os << "<xref linkend=\""
194                            << sgml::cleanID(buffer(), runparams, getParam("reference"))
195                            << "\">";
196                 }
197         } else {
198                 os << "<link linkend=\""
199                    << sgml::cleanID(buffer(), runparams, getParam("reference"))
200                    << "\">"
201                    << getParam("name")
202                    << "</link>";
203         }
204
205         return 0;
206 }
207
208
209 docstring InsetRef::xhtml(XHTMLStream & xs, OutputParams const &) const
210 {
211         docstring const & ref = getParam("reference");
212         InsetLabel const * il = buffer().insetLabel(ref);
213         string const & cmd = params().getCmdName();
214         docstring display_string;
215
216         if (il && !il->counterValue().empty()) {
217                 // Try to construct a label from the InsetLabel we reference.
218                 docstring const & value = il->counterValue();
219                 if (cmd == "ref")
220                         display_string = value;
221                 else if (cmd == "vref")
222                         // normally, would be "ref on page #", but we have no pages
223                         display_string = value;
224                 else if (cmd == "pageref" || cmd == "vpageref")
225                         // normally would be "on page #", but we have no pages
226                         display_string = _("elsewhere");
227                 else if (cmd == "eqref")
228                         display_string = bformat(from_ascii("equation (%1$s)"), value);
229                 else if (cmd == "formatted"
230                          // we don't really have the ability to handle these 
231                          // properly in XHTML output
232                          || cmd == "nameref")
233                         display_string = il->prettyCounter();
234         } else 
235                         display_string = ref;
236
237         // FIXME What we'd really like to do is to be able to output some
238         // appropriate sort of text here. But to do that, we need to associate
239         // some sort of counter with the label, and we don't have that yet.
240         string const attr = "href=\"#" + html::cleanAttr(to_utf8(ref)) + "\"";
241         xs << html::StartTag("a", attr);
242         xs << display_string;
243         xs << html::EndTag("a");
244         return docstring();
245 }
246
247
248 void InsetRef::toString(odocstream & os) const
249 {
250         odocstringstream ods;
251         plaintext(ods, OutputParams(0));
252         os << ods.str();
253 }
254
255
256 void InsetRef::forToc(docstring & os, size_t) const
257 {
258         // There's no need for details in the TOC, and a long label
259         // will just get in the way.
260         os += '#';
261 }
262
263
264 void InsetRef::updateBuffer(ParIterator const & it, UpdateType)
265 {
266         docstring const & ref = getParam("reference");
267         // register this inset into the buffer reference cache.
268         buffer().references(ref).push_back(make_pair(this, it));
269
270         docstring label;
271         for (int i = 0; !types[i].latex_name.empty(); ++i) {
272                 if (getCmdName() == types[i].latex_name) {
273                         label = _(types[i].short_gui_name);
274                         break;
275                 }
276         }
277         label += ref;
278         
279         if (!buffer().params().isLatex() && !getParam("name").empty()) {
280                 label += "||";
281                 label += getParam("name");
282         }
283         
284         screen_label_ = label;
285         bool shortened = false;
286         unsigned int const maxLabelChars = 24;
287         if (screen_label_.size() > maxLabelChars) {
288                 screen_label_.erase(maxLabelChars - 3);
289                 screen_label_ += "...";
290                 shortened = true;
291         }
292         if (shortened)
293                 tooltip_ = label;
294         else 
295                 tooltip_ = from_ascii("");
296 }
297
298
299 void InsetRef::addToToc(DocIterator const & cpit, bool output_active) const
300 {
301         docstring const & label = getParam("reference");
302         if (buffer().insetLabel(label))
303                 // This InsetRef has already been taken care of in InsetLabel::addToToc().
304                 return;
305
306         // It seems that this reference does not point to any valid label.
307         screen_label_ = _("BROKEN: ") + screen_label_;
308         Toc & toc = buffer().tocBackend().toc("label");
309         toc.push_back(TocItem(cpit, 0, screen_label_, output_active));
310 }
311
312
313 void InsetRef::validate(LaTeXFeatures & features) const
314 {
315         string const cmd = getCmdName();
316         if (cmd == "vref" || cmd == "vpageref")
317                 features.require("varioref");
318         else if (cmd == "formatted") {
319                 docstring const data = getEscapedLabel(features.runparams());
320                 docstring label;
321                 docstring prefix;
322                 string const fcmd = to_utf8(getFormattedCmd(data, label, prefix));
323                 if (buffer().params().use_refstyle) {
324                         features.require("refstyle");
325                         if (prefix == "cha")
326                                 features.addPreambleSnippet("\\let\\charef=\\chapref");
327                         else if (!prefix.empty()) {
328                                 string lcmd = "\\AtBeginDocument{\\providecommand" + 
329                                                 fcmd + "[1]{\\ref{" + to_utf8(prefix) + ":#1}}}";
330                                 features.addPreambleSnippet(lcmd);
331                         }
332                 } else {
333                         features.require("prettyref");
334                         // prettyref uses "cha" for chapters, so we provide a kind of
335                         // translation.
336                         if (prefix == "chap")
337                                 features.addPreambleSnippet("\\let\\pr@chap=\\pr@cha");
338                 }
339         } else if (cmd == "eqref" && !buffer().params().use_refstyle)
340                 // with refstyle, we simply output "(\ref{label})"
341                 features.require("amsmath");
342         else if (cmd == "nameref")
343                 features.require("nameref");
344 }
345
346
347 InsetRef::type_info InsetRef::types[] = {
348         { "ref",       N_("Standard"),              N_("Ref: ")},
349         { "eqref",     N_("Equation"),              N_("EqRef: ")},
350         { "pageref",   N_("Page Number"),           N_("Page: ")},
351         { "vpageref",  N_("Textual Page Number"),   N_("TextPage: ")},
352         { "vref",      N_("Standard+Textual Page"), N_("Ref+Text: ")},
353         { "formatted", N_("Formatted"),             N_("Format: ")},
354         { "nameref",   N_("Reference to Name"),     N_("NameRef:")},
355         { "", "", "" }
356 };
357
358
359 int InsetRef::getType(string const & name)
360 {
361         for (int i = 0; !types[i].latex_name.empty(); ++i)
362                 if (name == types[i].latex_name)
363                         return i;
364         return 0;
365 }
366
367
368 string const & InsetRef::getName(int type)
369 {
370         return types[type].latex_name;
371 }
372
373
374 } // namespace lyx