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