]> git.lyx.org Git - lyx.git/blob - src/insets/InsetHyperlink.cpp
Merge branch 'master' into biblatex2
[lyx.git] / src / insets / InsetHyperlink.cpp
1 /**
2  * \file InsetHyperlink.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  * \author Uwe Stöhr
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "InsetHyperlink.h"
15
16 #include "Buffer.h"
17 #include "DispatchResult.h"
18 #include "Encoding.h"
19 #include "Format.h"
20 #include "FuncRequest.h"
21 #include "FuncStatus.h"
22 #include "LaTeXFeatures.h"
23 #include "OutputParams.h"
24 #include "output_xhtml.h"
25 #include "sgml.h"
26 #include "texstream.h"
27
28 #include "support/docstream.h"
29 #include "support/FileName.h"
30 #include "support/filetools.h"
31 #include "support/gettext.h"
32 #include "support/lstrings.h"
33
34 #include "frontends/alert.h"
35
36 using namespace std;
37 using namespace lyx::support;
38
39 namespace lyx {
40
41
42 InsetHyperlink::InsetHyperlink(Buffer * buf, InsetCommandParams const & p)
43         : InsetCommand(buf, p)
44 {}
45
46
47 ParamInfo const & InsetHyperlink::findInfo(string const & /* cmdName */)
48 {
49         static ParamInfo param_info_;
50         if (param_info_.empty()) {
51                 param_info_.add("name", ParamInfo::LATEX_OPTIONAL);
52                 param_info_.add("target", ParamInfo::LATEX_REQUIRED);
53                 param_info_.add("type", ParamInfo::LATEX_REQUIRED);
54         }
55         return param_info_;
56 }
57
58
59 docstring InsetHyperlink::screenLabel() const
60 {
61         docstring const temp = _("Hyperlink: ");
62
63         docstring url;
64
65         url += getParam("name");
66         if (url.empty())
67                 url += getParam("target");
68
69         // elide if long
70         if (url.length() > 30) {
71                 docstring end = url.substr(url.length() - 17, url.length());
72                 support::truncateWithEllipsis(url, 13);
73                 url += end;
74         }
75         return temp + url;
76 }
77
78 void InsetHyperlink::doDispatch(Cursor & cur, FuncRequest & cmd)
79 {
80         switch (cmd.action()) {
81
82         case LFUN_INSET_EDIT:
83                 viewTarget();
84                 break;
85
86         default:
87                 InsetCommand::doDispatch(cur, cmd);
88                 break;
89         }
90 }
91
92
93 bool InsetHyperlink::getStatus(Cursor & cur, FuncRequest const & cmd,
94                 FuncStatus & flag) const
95 {
96         switch (cmd.action()) {
97         case LFUN_INSET_EDIT:
98                 flag.setEnabled(getParam("type").empty() || getParam("type") == "file:");
99                 return true;
100
101         default:
102                 return InsetCommand::getStatus(cur, cmd, flag);
103         }
104 }
105
106
107 void InsetHyperlink::viewTarget() const
108 {
109         if (getParam("type") == "file:") {
110                 FileName url = makeAbsPath(to_utf8(getParam("target")), buffer().filePath());
111                 string const format = formats.getFormatFromFile(url);
112                 formats.view(buffer(), url, format);
113         }
114 }
115
116
117 void InsetHyperlink::latex(otexstream & os,
118                            OutputParams const & runparams) const
119 {
120         docstring url = getParam("target");
121         docstring name = getParam("name");
122         static docstring const backslash = from_ascii("\\");
123         static docstring const braces = from_ascii("{}");
124         static char_type const chars_url[2] = {'%', '#'};
125         static char_type const chars_name[6] = {
126                 '&', '_', '$', '%', '#', '^'};
127
128         // For the case there is no name given, the target is set as name.
129         // Do this before !url.empty() and !name.empty() to handle characters
130         // like the "%" correctly.
131         if (name.empty())
132                 name = url;
133
134         if (!url.empty()) {
135                 // Replace the "\" character by its ASCII code according to the
136                 // URL specifications because "\" is not allowed in URLs and by
137                 // \href. Only do this when the following character is not also
138                 // a "\", because "\\" is valid code
139                 for (size_t i = 0, pos;
140                         (pos = url.find('\\', i)) != string::npos;
141                         i = pos + 2) {
142                         if (url[pos + 1] != '\\')
143                                 url.replace(pos, 1, from_ascii("%5C"));
144                 }
145
146                 // The characters in chars_url[] need to be escaped in the url
147                 // field because otherwise LaTeX will fail when the hyperlink is
148                 // within an argument of another command, e.g. in a \footnote. It
149                 // is important that they are escaped as "\#" and not as "\#{}".
150                 for (int k = 0; k < 2; k++)
151                         for (size_t i = 0, pos;
152                                 (pos = url.find(chars_url[k], i)) != string::npos;
153                                 i = pos + 2)
154                                 url.replace(pos, 1, backslash + chars_url[k]);
155                 
156                 // add "http://" when the type is web (type = empty)
157                 // and no "://" or "run:" is given
158                 docstring type = getParam("type");
159                 if (url.find(from_ascii("://")) == string::npos
160                         && url.find(from_ascii("run:")) == string::npos
161                         && type.empty())
162                         url = from_ascii("http://") + url;
163
164         } // end if (!url.empty())
165
166         // The characters in chars_name[] need to be changed to a command when
167         // they are in the name field.
168         if (!name.empty()) {
169                 // handle the "\" character, but only when the following character
170                 // is not also a "\", because "\\" is valid code
171                 docstring const textbackslash = from_ascii("\\textbackslash{}");
172                 for (size_t i = 0, pos;
173                         (pos = name.find('\\', i)) != string::npos;
174                         i = pos + 2) {
175                         if (name[pos + 1] != '\\')
176                                 name.replace(pos, 1, textbackslash);
177                 }
178                 // The characters in chars_name[] need to be changed to a command
179                 // when they are in the name field.
180                 // Therefore the treatment of "\" must be the first thing
181                 for (int k = 0; k < 6; k++)
182                         for (size_t i = 0, pos;
183                                 (pos = name.find(chars_name[k], i)) != string::npos;
184                                 i = pos + 2)
185                                 name.replace(pos, 1, backslash + chars_name[k] + braces);
186
187                 // replace the tilde by the \sim character as suggested in the
188                 // LaTeX FAQ for URLs
189                 docstring const sim = from_ascii("$\\sim$");
190                 for (size_t i = 0, pos;
191                         (pos = name.find('~', i)) != string::npos;
192                         i = pos + 1)
193                         name.replace(pos, 1, sim);
194                 pair<docstring, docstring> name_latexed =
195                         runparams.encoding->latexString(name, runparams.dryrun);
196                 name = name_latexed.first;
197                 if (!name_latexed.second.empty() && !runparams.silent) {
198                         // issue a warning about omitted characters
199                         // FIXME: should be passed to the error dialog
200                         frontend::Alert::warning(_("Uncodable characters"),
201                                 bformat(_("The following characters that are used in the href inset are not\n"
202                                           "representable in the current encoding and therefore have been omitted:\n%1$s."),
203                                         name_latexed.second));
204                 }
205         }  // end if (!name.empty())
206         
207         if (runparams.moving_arg)
208                 os << "\\protect";
209
210         // output the ready \href command
211         os << "\\href{" << getParam("type") << url << "}{" << name << '}';
212 }
213
214
215 int InsetHyperlink::plaintext(odocstringstream & os,
216         OutputParams const &, size_t) const
217 {
218         odocstringstream oss;
219
220         oss << '[' << getParam("target");
221         if (getParam("name").empty())
222                 oss << ']';
223         else
224                 oss << "||" << getParam("name") << ']';
225
226         docstring const str = oss.str();
227         os << str;
228         return str.size();
229 }
230
231
232 int InsetHyperlink::docbook(odocstream & os, OutputParams const &) const
233 {
234         os << "<ulink url=\""
235            << subst(getParam("target"), from_ascii("&"), from_ascii("&amp;"))
236            << "\">"
237            << sgml::escapeString(getParam("name"))
238            << "</ulink>";
239         return 0;
240 }
241
242
243 docstring InsetHyperlink::xhtml(XHTMLStream & xs, OutputParams const &) const
244 {
245         docstring const & target = 
246                 html::htmlize(getParam("target"), XHTMLStream::ESCAPE_AND);
247         docstring const & name   = getParam("name");
248         xs << html::StartTag("a", to_utf8("href=\"" + target + "\""));
249         xs << (name.empty() ? target : name);
250         xs << html::EndTag("a");
251         return docstring();
252 }
253
254
255 void InsetHyperlink::toString(odocstream & os) const
256 {
257         odocstringstream ods;
258         plaintext(ods, OutputParams(0), INT_MAX);
259         os << ods.str();
260 }
261
262
263 void InsetHyperlink::forOutliner(docstring & os, size_t const, bool const) const
264 {
265         docstring const & n = getParam("name");
266         if (!n.empty()) {
267                 os += n;
268                 return;
269         }
270         os += getParam("target");
271 }
272
273
274 docstring InsetHyperlink::toolTip(BufferView const & /*bv*/, int /*x*/, int /*y*/) const
275 {
276         docstring url = getParam("target");
277         docstring type = getParam("type");
278         docstring guitype = _("www");
279         if (type == "mailto:")
280                 guitype = _("email");
281         else if (type == "file:")
282                 guitype = _("file");
283         return bformat(_("Hyperlink (%1$s) to %2$s"), guitype, url);
284 }
285
286
287 void InsetHyperlink::validate(LaTeXFeatures & features) const
288 {
289         features.require("hyperref");
290 }
291
292
293 string InsetHyperlink::contextMenuName() const
294 {
295         return "context-hyperlink";
296 }
297
298
299 } // namespace lyx