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