]> git.lyx.org Git - lyx.git/blob - src/insets/InsetRef.cpp
Be more careful here about isalpha and isalnum. Per Enrico's suggestion,
[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                 char_type c = prefix[i];
118                 if (c >= 0x80 || !isalpha(prefix[i])) {
119                         LYXERR0("Prefix `" << prefix << "' is invalid for LaTeX.");
120                         // restore the label
121                         label = ref;
122                         return defcmd;
123                 }
124         }
125         return from_ascii("\\") + prefix + from_ascii("ref");
126 }
127
128
129 docstring InsetRef::getEscapedLabel(OutputParams const & rp) const
130 {
131         InsetCommandParams const & p = params();
132         ParamInfo const & pi = p.info();
133         ParamInfo::ParamData const & pd = pi["reference"];
134         return p.prepareCommand(rp, getParam("reference"), pd.handling());              
135 }
136
137
138 int InsetRef::latex(odocstream & os, OutputParams const & rp) const
139 {
140         string const cmd = getCmdName();
141         if (cmd != "formatted") {
142                 // We don't want to output p_["name"], since that is only used 
143                 // in docbook. So we construct new params, without it, and use that.
144                 InsetCommandParams p(REF_CODE, cmd);
145                 docstring const ref = getParam("reference");
146                 p["reference"] = ref;
147                 os << p.getCommand(rp);
148                 return 0;
149         } 
150         
151         // so we're doing a formatted reference.
152         docstring const data = getEscapedLabel(rp);
153         docstring label;
154         docstring prefix;
155         docstring const fcmd = getFormattedCmd(data, label, prefix);
156         os << fcmd << '{' << label << '}';
157         return 0;
158 }
159
160
161 int InsetRef::plaintext(odocstream & os, OutputParams const &) const
162 {
163         docstring const str = getParam("reference");
164         os << '[' << str << ']';
165         return 2 + str.size();
166 }
167
168
169 int InsetRef::docbook(odocstream & os, OutputParams const & runparams) const
170 {
171         docstring const & name = getParam("name");
172         if (name.empty()) {
173                 if (runparams.flavor == OutputParams::XML) {
174                         os << "<xref linkend=\""
175                            << sgml::cleanID(buffer(), runparams, getParam("reference"))
176                            << "\" />";
177                 } else {
178                         os << "<xref linkend=\""
179                            << sgml::cleanID(buffer(), runparams, getParam("reference"))
180                            << "\">";
181                 }
182         } else {
183                 os << "<link linkend=\""
184                    << sgml::cleanID(buffer(), runparams, getParam("reference"))
185                    << "\">"
186                    << getParam("name")
187                    << "</link>";
188         }
189
190         return 0;
191 }
192
193
194 docstring InsetRef::xhtml(XHTMLStream & xs, OutputParams const &) const
195 {
196         docstring const & ref = getParam("reference");
197         InsetLabel const * il = buffer().insetLabel(ref);
198         string const & cmd = params().getCmdName();
199         docstring display_string;
200
201         if (il && !il->counterValue().empty()) {
202                 // Try to construct a label from the InsetLabel we reference.
203                 docstring const & value = il->counterValue();
204                 if (cmd == "ref")
205                         display_string = value;
206                 else if (cmd == "vref")
207                         // normally, would be "ref on page #", but we have no pages
208                         display_string = value;
209                 else if (cmd == "pageref" || cmd == "vpageref")
210                         // normally would be "on page #", but we have no pages
211                         display_string = _("elsewhere");
212                 else if (cmd == "eqref")
213                         display_string = bformat(from_ascii("equation (%1$s)"), value);
214                 else if (cmd == "prettyref" 
215                          // we don't really have the ability to handle these 
216                          // properly in XHTML output
217                          || cmd == "nameref")
218                         display_string = il->prettyCounter();
219         } else 
220                         display_string = ref;
221
222         // FIXME What we'd really like to do is to be able to output some
223         // appropriate sort of text here. But to do that, we need to associate
224         // some sort of counter with the label, and we don't have that yet.
225         string const attr = "href=\"#" + html::cleanAttr(to_utf8(ref)) + "\"";
226         xs << html::StartTag("a", attr);
227         xs << display_string;
228         xs << html::EndTag("a");
229         return docstring();
230 }
231
232
233 void InsetRef::tocString(odocstream & os) const
234 {
235         plaintext(os, OutputParams(0));
236 }
237
238
239 void InsetRef::updateBuffer(ParIterator const & it, UpdateType)
240 {
241         docstring const & ref = getParam("reference");
242         // register this inset into the buffer reference cache.
243         buffer().references(ref).push_back(make_pair(this, it));
244
245         docstring label;
246         for (int i = 0; !types[i].latex_name.empty(); ++i) {
247                 if (getCmdName() == types[i].latex_name) {
248                         label = _(types[i].short_gui_name);
249                         break;
250                 }
251         }
252         label += ref;
253         
254         if (!buffer().isLatex() && !getParam("name").empty()) {
255                 label += "||";
256                 label += getParam("name");
257         }
258         
259         screen_label_ = label;
260         bool shortened = false;
261         unsigned int const maxLabelChars = 24;
262         if (screen_label_.size() > maxLabelChars) {
263                 screen_label_.erase(maxLabelChars - 3);
264                 screen_label_ += "...";
265                 shortened = true;
266         }
267         if (shortened)
268                 tooltip_ = label;
269         else 
270                 tooltip_ = from_ascii("");
271 }
272
273
274 void InsetRef::addToToc(DocIterator const & cpit)
275 {
276         docstring const & label = getParam("reference");
277         if (buffer().insetLabel(label))
278                 // This InsetRef has already been taken care of in InsetLabel::addToToc().
279                 return;
280
281         // It seems that this reference does not point to any valid label.
282         screen_label_ = _("BROKEN: ") + screen_label_;
283         Toc & toc = buffer().tocBackend().toc("label");
284         toc.push_back(TocItem(cpit, 0, screen_label_));
285 }
286
287
288 void InsetRef::validate(LaTeXFeatures & features) const
289 {
290         string const cmd = getCmdName();
291         if (cmd == "vref" || cmd == "vpageref")
292                 features.require("varioref");
293         else if (getCmdName() == "formatted") {
294                 docstring const data = getEscapedLabel(features.runparams());
295                 docstring label;
296                 docstring prefix;
297                 if (buffer().params().use_refstyle) {
298                         features.require("refstyle");
299                         string const fcmd = to_utf8(getFormattedCmd(data, label, prefix));
300                         if (!prefix.empty()) {
301                                 string lcmd = "\\AtBeginDocument{\\providecommand" + 
302                                                 fcmd + "[1]{\\ref{" + to_utf8(prefix) + ":#1}}}";
303                                 features.addPreambleSnippet(lcmd);
304                         } else if (prefix == "cha")
305                                 features.addPreambleSnippet("\\let\\charef=\\chapref");
306                 } else {
307                         features.require("prettyref");
308                         // prettyref uses "cha" for chapters, so we provide a kind of
309                         // translation.
310                         if (prefix == "chap")
311                                 features.addPreambleSnippet("\\let\\pr@chap=\\pr@cha");
312                 }
313         } else if (getCmdName() == "eqref" && !buffer().params().use_refstyle)
314                 // refstyle defines its own version
315                 features.require("amsmath");
316         else if (cmd == "nameref")
317                 features.require("nameref");
318 }
319
320
321 InsetRef::type_info InsetRef::types[] = {
322         { "ref",       N_("Standard"),              N_("Ref: ")},
323         { "eqref",     N_("Equation"),              N_("EqRef: ")},
324         { "pageref",   N_("Page Number"),           N_("Page: ")},
325         { "vpageref",  N_("Textual Page Number"),   N_("TextPage: ")},
326         { "vref",      N_("Standard+Textual Page"), N_("Ref+Text: ")},
327         { "formatted", N_("Formatted"),             N_("Format: ")},
328         { "nameref",   N_("Reference to Name"),     N_("NameRef:")},
329         { "", "", "" }
330 };
331
332
333 int InsetRef::getType(string const & name)
334 {
335         for (int i = 0; !types[i].latex_name.empty(); ++i)
336                 if (name == types[i].latex_name)
337                         return i;
338         return 0;
339 }
340
341
342 string const & InsetRef::getName(int type)
343 {
344         return types[type].latex_name;
345 }
346
347
348 } // namespace lyx