]> git.lyx.org Git - features.git/blob - src/KeyMap.cpp
Do not allow pasting backslashes in macro names
[features.git] / src / KeyMap.cpp
1 /**
2  * \file KeyMap.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Jean-Marc Lasgouttes
8  * \author John Levon
9  * \author André Pönitz
10  *
11  * Full author contact details are available in file CREDITS.
12  */
13
14 #include <config.h>
15
16 #include "KeyMap.h"
17
18 #include "KeySequence.h"
19 #include "LyXAction.h"
20 #include "Lexer.h"
21
22 #include "support/debug.h"
23 #include "support/docstream.h"
24 #include "support/FileName.h"
25 #include "support/filetools.h"
26 #include "support/gettext.h"
27 #include "support/lstrings.h"
28 #include "support/TempFile.h"
29
30 #include "frontends/alert.h"
31
32 #include <fstream>
33 #include <sstream>
34 #include <utility>
35
36 using namespace std;
37 using namespace lyx::support;
38
39 namespace lyx {
40
41 string const KeyMap::printKeySym(KeySymbol const & key, KeyModifier mod)
42 {
43         string buf;
44
45         string const s = key.getSymbolName();
46
47         if (mod & ControlModifier)
48                 buf += "C-";
49 #if defined(USE_MACOSX_PACKAGING) || defined(USE_META_KEYBINDING)
50         if (mod & MetaModifier)
51                 buf += "M-";
52         if (mod & AltModifier)
53                 buf += "A-";
54 #else
55         if (mod & AltModifier)
56                 buf += "M-";
57 #endif
58         if (mod & ShiftModifier)
59                 buf += "S-";
60
61         buf += s;
62         return buf;
63 }
64
65
66 size_t KeyMap::bind(string const & seq, FuncRequest const & func)
67 {
68         LYXERR(Debug::KBMAP, "BIND: Sequence `" << seq << "' Action `"
69                << func.action() << '\'');
70
71         KeySequence k(nullptr, nullptr);
72
73         string::size_type const res = k.parse(seq);
74         if (res == string::npos) {
75                 bind(&k, func);
76         } else {
77                 LYXERR(Debug::KBMAP, "Parse error at position " << res
78                                      << " in key sequence '" << seq << "'.");
79         }
80
81         return res == string::npos ? 0 : res;
82 }
83
84
85 size_t KeyMap::unbind(string const & seq, FuncRequest const & func)
86 {
87         KeySequence k(nullptr, nullptr);
88
89         string::size_type const res = k.parse(seq);
90         if (res == string::npos)
91                 unbind(&k, func);
92         else
93                 LYXERR(Debug::KBMAP, "Parse error at position " << res
94                                      << " in key sequence '" << seq << "'.");
95         return res == string::npos ? 0 : res;
96 }
97
98
99 void KeyMap::bind(KeySequence * seq, FuncRequest const & func, unsigned int r)
100 {
101         KeySymbol code = seq->sequence[r];
102         if (!code.isOK())
103                 return;
104
105         KeyModifier const mod1 = seq->modifiers[r].first;
106         KeyModifier const mod2 = seq->modifiers[r].second;
107
108         // check if key is already there
109         // FIXME perf: Profiling shows that this is responsible of 99% of the
110         // cost of GuiPrefs::applyView()
111         Table::iterator end = table.end();
112         for (Table::iterator it = table.begin(); it != end; ++it) {
113                 if (code == it->code
114                     && mod1 == it->mod.first
115                     && mod2 == it->mod.second) {
116                         // overwrite binding
117                         if (r + 1 == seq->length()) {
118                                 LYXERR(Debug::KBMAP, "Warning: New binding for '"
119                                         << to_utf8(seq->print(KeySequence::Portable))
120                                         << "' is overriding old binding...");
121                                 if (it->prefixes)
122                                         it->prefixes.reset();
123                                 it->func = func;
124                                 it->func.setOrigin(FuncRequest::KEYBOARD);
125                                 return;
126                         } else if (!it->prefixes) {
127                                 lyxerr << "Error: New binding for '"
128                                        << to_utf8(seq->print(KeySequence::Portable))
129                                        << "' is overriding old binding..."
130                                        << endl;
131                                 return;
132                         } else {
133                                 it->prefixes->bind(seq, func, r + 1);
134                                 return;
135                         }
136                 }
137         }
138
139         Table::iterator newone = table.insert(table.end(), Key());
140         newone->code = code;
141         newone->mod = seq->modifiers[r];
142         if (r + 1 == seq->length()) {
143                 newone->func = func;
144                 newone->func.setOrigin(FuncRequest::KEYBOARD);
145                 newone->prefixes.reset();
146         } else {
147                 newone->prefixes.reset(new KeyMap);
148                 newone->prefixes->bind(seq, func, r + 1);
149         }
150 }
151
152
153 void KeyMap::unbind(KeySequence * seq, FuncRequest const & func, unsigned int r)
154 {
155         KeySymbol code = seq->sequence[r];
156         if (!code.isOK())
157                 return;
158
159         KeyModifier const mod1 = seq->modifiers[r].first;
160         KeyModifier const mod2 = seq->modifiers[r].second;
161
162         // check if key is already there
163         vector <Table::iterator> removes;
164         Table::iterator end = table.end();
165         for (Table::iterator it = table.begin(); it != end; ++it) {
166                 if (code == it->code
167                     && mod1 == it->mod.first
168                     && mod2 == it->mod.second) {
169                         // remove
170                         if (r + 1 == seq->length()) {
171                                 if (it->func == func || func == FuncRequest::unknown) {
172                                         removes.push_back(it);
173                                         if (it->prefixes)
174                                                 it->prefixes.reset();
175                                 }
176                         } else if (it->prefixes) {
177                                 it->prefixes->unbind(seq, func, r + 1);
178                                 if (it->prefixes->empty())
179                                         removes.push_back(it);
180                                 return;
181                         }
182                 }
183         }
184
185         for (unsigned i = removes.size(); i > 0; --i)
186                 table.erase(removes[i-1]);
187 }
188
189
190 FuncRequest KeyMap::getBinding(KeySequence const & seq, unsigned int r)
191 {
192         KeySymbol code = seq.sequence[r];
193         if (!code.isOK())
194                 return FuncRequest::unknown;
195
196         KeyModifier const mod1 = seq.modifiers[r].first;
197         KeyModifier const mod2 = seq.modifiers[r].second;
198
199         // check if key is already there
200         Table::iterator end = table.end();
201         for (Table::iterator it = table.begin(); it != end; ++it) {
202                 if (code == it->code
203                     && mod1 == it->mod.first
204                     && mod2 == it->mod.second) {
205                         if (r + 1 == seq.length())
206                                 return it->func;
207                         else if (it->prefixes)
208                                 return it->prefixes->getBinding(seq, r + 1);
209                 }
210         }
211         return FuncRequest::unknown;
212 }
213
214
215 void KeyMap::clear()
216 {
217         table.clear();
218 }
219
220
221 bool KeyMap::read(string const & bind_file, KeyMap * unbind_map, BindReadType rt)
222 {
223         FileName bf = i18nLibFileSearch("bind", bind_file, "bind");
224         if (bf.empty()) {
225                 if (rt == MissingOK)
226                         return true;
227
228                 lyxerr << "Could not find bind file: " << bind_file;
229                 if (rt == Default) {
230                         frontend::Alert::warning(_("Could not find bind file"),
231                                 bformat(_("Unable to find the bind file\n%1$s.\n"
232                                                 "Please check your installation."), from_utf8(bind_file)));
233                         return false;
234                 }
235
236                 static string const defaultBindfile = "cua";
237                 if (bind_file == defaultBindfile) {
238                         frontend::Alert::warning(_("Could not find `cua.bind' file"),
239                                 _("Unable to find the default bind file `cua.bind'.\n"
240                                    "Please check your installation."));
241                         return false;
242                 }
243
244                 // Try it with the default file.
245                 frontend::Alert::warning(_("Could not find bind file"),
246                         bformat(_("Unable to find the bind file\n%1$s.\n"
247                                   "Falling back to default."), from_utf8(bind_file)));
248                 return read(defaultBindfile, unbind_map);
249         }
250         return read(bf, unbind_map);
251 }
252
253
254 bool KeyMap::read(FileName const & bind_file, KeyMap * unbind_map)
255 {
256         ReturnValues retval = readWithoutConv(bind_file, unbind_map);
257         if (retval != FormatMismatch)
258                 return retval == ReadOK;
259
260         LYXERR(Debug::FILES, "Converting bind file to " << LFUN_FORMAT);
261         TempFile tmp("convert_bind");
262         FileName const tempfile = tmp.name();
263         bool const success = prefs2prefs(bind_file, tempfile, true);
264         if (!success) {
265                 LYXERR0 ("Unable to convert " << bind_file <<
266                         " to format " << LFUN_FORMAT);
267                 return false;
268         }
269         retval = readWithoutConv(tempfile, unbind_map);
270         return retval == ReadOK;
271 }
272
273
274 KeyMap::ReturnValues KeyMap::readWithoutConv(FileName const & bind_file, KeyMap * unbind_map)
275 {
276         enum {
277                 BN_BIND,
278                 BN_BINDFILE,
279                 BN_FORMAT,
280                 BN_UNBIND
281         };
282
283         LexerKeyword bindTags[] = {
284                 { "\\bind",      BN_BIND },
285                 { "\\bind_file", BN_BINDFILE },
286                 { "\\unbind",    BN_UNBIND },
287                 { "format",      BN_FORMAT }
288         };
289
290         Lexer lexrc(bindTags);
291         if (lyxerr.debugging(Debug::PARSER))
292                 lexrc.printTable(lyxerr);
293
294         lexrc.setFile(bind_file);
295         if (!lexrc.isOK()) {
296                 LYXERR0("KeyMap::read: cannot open bind file:" << bind_file.absFileName());
297                 return FileError;
298         }
299
300         LYXERR(Debug::KBMAP, "Reading bind file:" << bind_file.absFileName());
301
302         // format of pre-2.0 bind files, before this tag was introduced.
303         int format = 0;
304         bool error = false;
305         while (lexrc.isOK()) {
306                 switch (lexrc.lex()) {
307
308                 case Lexer::LEX_UNDEF:
309                         lexrc.printError("Unknown tag `$$Token'");
310                         error = true;
311                         continue;
312
313                 case Lexer::LEX_FEOF:
314                         continue;
315
316                 case BN_FORMAT:
317                         if (lexrc.next())
318                                 format = lexrc.getInteger();
319                         break;
320
321                 case BN_BIND: {
322                         if (!lexrc.next()) {
323                                 lexrc.printError("BN_BIND: Missing key sequence");
324                                 error = true;
325                                 break;
326                         }
327                         string seq = lexrc.getString();
328
329                         if (!lexrc.next(true)) {
330                                 lexrc.printError("BN_BIND: missing command");
331                                 error = true;
332                                 break;
333                         }
334                         string cmd = lexrc.getString();
335
336                         FuncRequest func = lyxaction.lookupFunc(cmd);
337                         if (func == FuncRequest::unknown) {
338                                 lexrc.printError("BN_BIND: Unknown LyX function `$$Token'");
339                                 error = true;
340                                 break;
341                         }
342
343                         bind(seq, func);
344                         break;
345                 }
346
347                 case BN_UNBIND: {
348                         if (!lexrc.next()) {
349                                 lexrc.printError("BN_UNBIND: Missing key sequence");
350                                 error = true;
351                                 break;
352                         }
353                         string seq = lexrc.getString();
354
355                         if (!lexrc.next(true)) {
356                                 lexrc.printError("BN_UNBIND: missing command");
357                                 error = true;
358                                 break;
359                         }
360                         string cmd = lexrc.getString();
361                         FuncRequest func;
362                         if (cmd == "*")
363                                 func = FuncRequest::unknown;
364                         else {
365                                 func = lyxaction.lookupFunc(cmd);
366                                 if (func == FuncRequest::unknown) {
367                                         lexrc.printError("BN_UNBIND: Unknown LyX function `$$Token'");
368                                         error = true;
369                                         break;
370                                 }
371                         }
372
373                         if (unbind_map)
374                                 unbind_map->bind(seq, func);
375                         else
376                                 unbind(seq, func);
377                         break;
378                 }
379
380                 case BN_BINDFILE:
381                         if (!lexrc.next()) {
382                                 lexrc.printError("BN_BINDFILE: Missing file name");
383                                 error = true;
384                                 break;
385                         }
386                         string const tmp = lexrc.getString();
387                         error |= !read(tmp, unbind_map);
388                         break;
389                 }
390
391                 // This is triggered the first time through the loop unless
392                 // we hit a format tag.
393                 if (format != LFUN_FORMAT)
394                         return FormatMismatch;
395         }
396
397         if (error) {
398                 LYXERR0("KeyMap::read: error while reading bind file:" << bind_file.absFileName());
399                 return ReadError;
400         }
401         return ReadOK;
402 }
403
404
405 void KeyMap::write(string const & bind_file, bool append, bool unbind) const
406 {
407         ofstream os(bind_file.c_str(),
408                 append ? (ios::app | ios::out) : ios::out);
409
410         if (!append)
411                 os << "## This file is automatically generated by lyx\n"
412                    << "## All modifications will be lost\n\n"
413                    << "Format " << LFUN_FORMAT << "\n\n";
414
415         string tag = unbind ? "\\unbind" : "\\bind";
416         for (auto const & bnd : listBindings(false)) {
417                 FuncCode const action = bnd.request.action();
418                 string const arg = to_utf8(bnd.request.argument());
419
420                 string cmd;
421                 if (unbind && bnd.request == FuncRequest::unknown)
422                         cmd = "*";
423                 else
424                         cmd = lyxaction.getActionName(action) + (arg.empty() ? string() : " " + arg);
425                 os << tag << " \""
426                    << to_utf8(bnd.sequence.print(KeySequence::BindFile))
427                    << "\" " << Lexer::quoteString(cmd)
428                    << "\n";
429         }
430         os << "\n";
431         os.close();
432 }
433
434
435 FuncRequest const & KeyMap::lookup(KeySymbol const &key,
436                   KeyModifier mod, KeySequence * seq) const
437 {
438         if (table.empty()) {
439                 seq->reset();
440                 return FuncRequest::unknown;
441         }
442
443         Table::const_iterator end = table.end();
444         for (Table::const_iterator cit = table.begin(); cit != end; ++cit) {
445                 KeyModifier mask = cit->mod.second;
446                 KeyModifier check = static_cast<KeyModifier>(mod & ~mask);
447
448                 if (cit->code == key && cit->mod.first == check) {
449                         // match found
450                         if (cit->prefixes) {
451                                 // this is a prefix key - set new map
452                                 seq->curmap = cit->prefixes.get();
453                                 static const FuncRequest prefix(LFUN_COMMAND_PREFIX);
454                                 return prefix;
455                         } else {
456                                 // final key - reset map
457                                 seq->reset();
458                                 return cit->func;
459                         }
460                 }
461         }
462
463         // error - key not found:
464         seq->reset();
465
466         return FuncRequest::unknown;
467 }
468
469
470 docstring const KeyMap::print(bool forgui) const
471 {
472         docstring buf;
473         Table::const_iterator end = table.end();
474         for (Table::const_iterator cit = table.begin(); cit != end; ++cit) {
475                 buf += cit->code.print(cit->mod.first, forgui);
476                 buf += ' ';
477         }
478         return buf;
479 }
480
481
482 docstring KeyMap::printBindings(FuncRequest const & func,
483                                 KeySequence::outputFormat format,
484                                 bool const untranslated) const
485 {
486         Bindings bindings = findBindings(func);
487         if (bindings.empty())
488                 return docstring();
489
490         odocstringstream res;
491         Bindings::const_iterator cit = bindings.begin();
492         Bindings::const_iterator cit_end = bindings.end();
493         // print the first item
494         res << cit->print(format, untranslated);
495         // more than one shortcuts?
496         for (++cit; cit != cit_end; ++cit)
497                 res << ", " << cit->print(format, untranslated);
498         return res.str();
499 }
500
501
502 KeyMap::Bindings KeyMap::findBindings(FuncRequest const & func) const
503 {
504         return findBindings(func, KeySequence(nullptr, nullptr));
505 }
506
507
508 KeyMap::Bindings KeyMap::findBindings(FuncRequest const & func,
509                         KeySequence const & prefix) const
510 {
511         Bindings res;
512         if (table.empty())
513                 return res;
514
515         Table::const_iterator end = table.end();
516         for (Table::const_iterator cit = table.begin(); cit != end; ++cit) {
517                 if (cit->prefixes) {
518                         KeySequence seq = prefix;
519                         seq.addkey(cit->code, cit->mod.first);
520                         Bindings res2 = cit->prefixes->findBindings(func, seq);
521                         res.insert(res.end(), res2.begin(), res2.end());
522                 } else if (cit->func == func) {
523                         KeySequence seq = prefix;
524                         seq.addkey(cit->code, cit->mod.first);
525                         res.push_back(seq);
526                 }
527         }
528
529         return res;
530 }
531
532
533 KeyMap::BindingList KeyMap::listBindings(bool unbound, KeyMap::ItemType tag) const
534 {
535         BindingList list;
536         listBindings(list, KeySequence(nullptr, nullptr), tag);
537         if (unbound) {
538                 for (auto const & name_code : lyxaction) {
539                         FuncCode action = name_code.second;
540                         bool has_action = false;
541                         BindingList::const_iterator bit = list.begin();
542                         BindingList::const_iterator const ben = list.end();
543                         for (; bit != ben; ++bit)
544                                 if (bit->request.action() == action) {
545                                         has_action = true;
546                                         break;
547                                 }
548                         if (!has_action)
549                                 list.push_back(Binding(FuncRequest(action), KeySequence(nullptr, nullptr), tag));
550                 }
551         }
552         return list;
553 }
554
555
556 void KeyMap::listBindings(BindingList & list,
557         KeySequence const & prefix, KeyMap::ItemType tag) const
558 {
559         Table::const_iterator it = table.begin();
560         Table::const_iterator it_end = table.end();
561         for (; it != it_end; ++it) {
562                 // a LFUN_COMMAND_PREFIX
563                 if (it->prefixes) {
564                         KeySequence seq = prefix;
565                         seq.addkey(it->code, it->mod.first);
566                         it->prefixes->listBindings(list, seq, tag);
567                 } else {
568                         KeySequence seq = prefix;
569                         seq.addkey(it->code, it->mod.first);
570                         list.push_back(Binding(it->func, seq, tag));
571                 }
572         }
573 }
574
575
576 } // namespace lyx