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