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