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