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