]> git.lyx.org Git - lyx.git/blob - src/insets/InsetHyperlink.cpp
Disambiguate string
[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 #include "InsetHyperlink.h"
14
15 #include "Buffer.h"
16 #include "Format.h"
17 #include "FuncRequest.h"
18 #include "FuncStatus.h"
19 #include "LaTeXFeatures.h"
20 #include "output_docbook.h"
21 #include "output_xhtml.h"
22 #include "xml.h"
23 #include "texstream.h"
24
25 #include "support/debug.h"
26 #include "support/docstream.h"
27 #include "support/FileName.h"
28 #include "support/filetools.h"
29 #include "support/gettext.h"
30 #include "support/lstrings.h"
31 #include "support/qstring_helpers.h"
32
33 #include "frontends/alert.h"
34
35 #include <QtGui/QDesktopServices>
36 #include <QUrl>
37
38 using namespace std;
39 using namespace lyx::support;
40
41 namespace lyx {
42
43
44 InsetHyperlink::InsetHyperlink(Buffer * buf, InsetCommandParams const & p)
45         : InsetCommand(buf, p)
46 {}
47
48
49 ParamInfo const & InsetHyperlink::findInfo(string const & /* cmdName */)
50 {
51         static ParamInfo param_info_;
52         if (param_info_.empty()) {
53                 param_info_.add("name", ParamInfo::LATEX_OPTIONAL,
54                                 ParamInfo::HANDLING_LATEXIFY);
55                 param_info_.add("target", ParamInfo::LATEX_REQUIRED);
56                 param_info_.add("type", ParamInfo::LATEX_REQUIRED);
57                 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
58         }
59         return param_info_;
60 }
61
62
63 docstring InsetHyperlink::screenLabel() const
64 {
65         // TODO: replace with unicode hyperlink character = U+1F517
66         docstring const temp = _("Hyperlink: ");
67
68         docstring url;
69
70         url += getParam("name");
71         if (url.empty()) {
72                 url += getParam("target");
73
74                 // elide if long and no name was provided
75                 if (url.length() > 30) {
76                         docstring end = url.substr(url.length() - 17, url.length());
77                         support::truncateWithEllipsis(url, 13);
78                         url += end;
79                 }
80         } else {
81                 // elide if long (approx number of chars in line of article class)
82                 if (url.length() > 80) {
83                         docstring end = url.substr(url.length() - 67, url.length());
84                         support::truncateWithEllipsis(url, 13);
85                         url += end;
86                 }
87         }
88         return temp + url;
89 }
90
91
92 void InsetHyperlink::doDispatch(Cursor & cur, FuncRequest & cmd)
93 {
94         switch (cmd.action()) {
95
96         case LFUN_INSET_EDIT:
97                 viewTarget();
98                 break;
99
100         default:
101                 InsetCommand::doDispatch(cur, cmd);
102                 break;
103         }
104 }
105
106
107 bool InsetHyperlink::getStatus(Cursor & cur, FuncRequest const & cmd,
108                 FuncStatus & flag) const
109 {
110         switch (cmd.action()) {
111         case LFUN_INSET_EDIT: {
112                 docstring const & utype = getParam("type");
113                 QUrl url(toqstr(getParam("target")),QUrl::StrictMode);
114                 bool url_valid = utype.empty() && url.isValid();
115                 flag.setEnabled(url_valid || utype == "file:");
116                 return true;
117                 }
118
119         default:
120                 return InsetCommand::getStatus(cur, cmd, flag);
121         }
122 }
123
124
125 void InsetHyperlink::viewTarget() const
126 {
127         if (getParam("type").empty()) { //==Web
128                 QUrl url(toqstr(getParam("target")),QUrl::StrictMode);
129                 if (!QDesktopServices::openUrl(url))
130                         LYXERR0("Unable to open URL!");
131         } else if (getParam("type") == "file:") {
132                 FileName url = makeAbsPath(to_utf8(getParam("target")), buffer().filePath());
133                 string const format = theFormats().getFormatFromFile(url);
134                 theFormats().view(buffer(), url, format);
135         }
136 }
137
138
139 docstring makeURL(docstring const & url, docstring const & type) {
140         if (type == "other" ||
141                         (!type.empty() && url.find(type) == 0))
142                 return url;
143         return type + url;
144 }
145
146
147 void InsetHyperlink::latex(otexstream & os,
148                            OutputParams const & runparams) const
149 {
150         docstring url   = getParam("target");
151         docstring name  = getParam("name");
152         docstring const & utype = getParam("type");
153         static char_type const chars_url[2] = {'%', '#'};
154
155         // For the case there is no name given, the target is set as name.
156         // Do this before !url.empty() and !name.empty() to handle characters
157         // such as % correctly.
158         if (name.empty())
159                 name = url;
160
161         if (!url.empty()) {
162                 // Use URI/URL-style percent-encoded string (hexadecimal).
163                 // We exclude some characters that must not be transformed
164                 // in hrefs: % # / : ? = & ! * ' ( ) ; @ + $ , [ ]
165                 // or that we need to treat manually: \.
166                 url = to_percent_encoding(url, from_ascii("%#\\/:?=&!*'();@+$,[]"));
167                 // We handle \ manually since \\ is valid
168                 for (size_t i = 0, pos;
169                         (pos = url.find('\\', i)) != string::npos;
170                         i = pos + 2) {
171                         if (url[pos + 1] != '\\')
172                                 url.replace(pos, 1, from_ascii("%5C"));
173                 }
174
175                 // The characters in chars_url[] need to be escaped in the url
176                 // field because otherwise LaTeX will fail when the hyperlink is
177                 // within an argument of another command, e.g. in a \footnote. It
178                 // is important that they are escaped as "\#" and not as "\#{}".
179                 // FIXME this is not necessary in outside of commands.
180                 for (int k = 0; k < 2; k++)
181                         for (size_t i = 0, pos;
182                                 (pos = url.find(chars_url[k], i)) != string::npos;
183                                 i = pos + 2)
184                                 url.replace(pos, 1, from_ascii("\\") + chars_url[k]);
185
186                 // add "http://" when the type is web (type = empty)
187                 // and no "://" or "run:" is given
188                 if (url.find(from_ascii("://")) == string::npos
189                         && url.find(from_ascii("run:")) == string::npos
190                         && utype.empty())
191                         url = from_ascii("http://") + url;
192
193         } // end if (!url.empty())
194
195         if (!name.empty()) {
196                 name = params().prepareCommand(runparams, name,
197                                         ParamInfo::HANDLING_LATEXIFY);
198                 // replace the tilde by the \sim character as suggested in the
199                 // LaTeX FAQ for URLs
200                 if (getParam("literal") != "true") {
201                         docstring const sim = from_ascii("$\\sim$");
202                         for (size_t i = 0, pos;
203                                 (pos = name.find('~', i)) != string::npos;
204                                 i = pos + 1)
205                                 name.replace(pos, 1, sim);
206                 }
207         }
208
209         if (runparams.moving_arg)
210                 os << "\\protect";
211
212         // output the ready \href command
213         os << "\\href{" << makeURL(url, utype) << "}{" << name << '}';
214 }
215
216
217 int InsetHyperlink::plaintext(odocstringstream & os,
218         OutputParams const &, size_t) const
219 {
220         odocstringstream oss;
221
222         oss << '[' << getParam("target");
223         if (getParam("name").empty())
224                 oss << ']';
225         else
226                 oss << "||" << getParam("name") << ']';
227
228         docstring const str = oss.str();
229         os << str;
230         return str.size();
231 }
232
233
234 void InsetHyperlink::docbook(XMLStream & xs, OutputParams const &) const
235 {
236         docstring target = subst(getParam("target"), from_ascii("&"), from_ascii("&amp;")) ;
237         xs << xml::StartTag("link", "xlink:href=\"" + makeURL(target, getParam("type")) + "\"");
238         xs << xml::escapeString(getParam("name"));
239         xs << xml::EndTag("link");
240 }
241
242
243 docstring InsetHyperlink::xhtml(XMLStream & xs, OutputParams const &) const
244 {
245         docstring const & target =
246                 xml::escapeString(getParam("target"), XMLStream::ESCAPE_AND);
247         docstring const & name = getParam("name");
248         xs << xml::StartTag("a", to_utf8("href=\"" + makeURL(target, getParam("type")) + "\""));
249         xs << (name.empty() ? target : name);
250         xs << xml::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 const & url = getParam("target");
277         docstring const & type = getParam("type");
278         docstring guitype = _("www");
279         if (type == "mailto:")
280                 guitype = _("email");
281         else if (type == "file:")
282                 guitype = _("file");
283         else if (type == "other")
284                 guitype = _("other[[Hyperlink Type]]");
285         return bformat(_("Hyperlink (%1$s) to %2$s"), guitype, url);
286 }
287
288
289 void InsetHyperlink::validate(LaTeXFeatures & features) const
290 {
291         features.require("hyperref");
292         InsetCommand::validate(features);
293 }
294
295
296 pair<int, int> InsetHyperlink::isWords() const
297 {
298         docstring const label = getParam("name");
299         return pair<int, int>(label.size(), wordCount(label));
300 }
301
302
303 string InsetHyperlink::contextMenuName() const
304 {
305         return "context-hyperlink";
306 }
307
308
309 } // namespace lyx