]> git.lyx.org Git - lyx.git/blob - src/Trans.cpp
Fix #10778 (issue with CJK and language nesting)
[lyx.git] / src / Trans.cpp
1 /**
2  * \file Trans.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 Matthias Ettrich
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "Trans.h"
15
16 #include "Buffer.h"
17 #include "BufferView.h"
18 #include "Cursor.h"
19 #include "CutAndPaste.h"
20 #include "Lexer.h"
21 #include "LyXRC.h"
22 #include "Text.h"
23
24 #include "support/debug.h"
25 #include "support/docstream.h"
26 #include "support/FileName.h"
27 #include "support/filetools.h"
28 #include "support/lstrings.h"
29
30 using namespace std;
31 using namespace lyx::support;
32
33 namespace lyx {
34
35 /////////////////////////////////////////////////////////////////////
36 //
37 // TeXAccents
38 //
39 /////////////////////////////////////////////////////////////////////
40
41 /* the names used by TeX and XWindows for deadkeys/accents are not the same
42    so here follows a table to clearify the differences. Please correct this
43    if I got it wrong
44
45    |------------------|------------------|------------------|--------------|
46    |      TeX         |     XWindows     |   \bind/LFUN     | used by intl |
47    |------------------|------------------|------------------|--------------|
48    |    grave         |    grave         |LFUN_ACCENT_GRAVE        | grave
49    |    acute         |    acute         |LFUN_ACCENT_ACUTE        | acute
50    |    circumflex    |    circumflex    |LFUN_ACCENT_CIRCUMFLEX   | circumflex
51    | umlaut/dieresis  |    diaeresis     |LFUN_ACCENT_UMLAUT       | umlaut
52    |    tilde         |    tilde         |LFUN_ACCENT_TILDE        | tilde
53    |    macron        |    maron         |LFUN_ACCENT_MACRON       | macron
54    |    dot           |    abovedot      |LFUN_ACCENT_DOT          | dot
55    |    cedilla       |    cedilla       |LFUN_ACCENT_CEDILLA      | cedilla
56    |    underdot      |                  |LFUN_ACCENT_UNDERDOT     | underdot
57    |    underbar      |                  |LFUN_ACCENT_UNDERBAR     | underbar
58    |    hácek         |    caron         |LFUN_ACCENT_CARON        | caron
59    |    breve         |    breve         |LFUN_ACCENT_BREVE        | breve
60    |    tie           |                  |LFUN_ACCENT_TIE          | tie
61    | Hungarian umlaut |    doubleacute   |LFUN_ACCENT_HUNGARIAN_UMLAUT  | hungarian umlaut
62    |    circle        |    abovering     |LFUN_ACCENT_CIRCLE       | circle
63    |                  |    ogonek        |                  |
64    |                  |    iota          |                  |
65    |                  |    voiced_sound  |                  |
66    |                  | semivoiced_sound |                  |
67    */
68 static TeXAccent lyx_accent_table[] = {
69         {TEX_NOACCENT,   0,      "",                LFUN_NOACTION},
70         {TEX_ACUTE,      0x0301, "acute",           LFUN_ACCENT_ACUTE},
71         {TEX_GRAVE,      0x0300, "grave",           LFUN_ACCENT_GRAVE},
72         {TEX_MACRON,     0x0304, "macron",          LFUN_ACCENT_MACRON},
73         {TEX_TILDE,      0x0303, "tilde",           LFUN_ACCENT_TILDE},
74         {TEX_PERISPOMENI, 0x0342, "perispomeni",    LFUN_ACCENT_PERISPOMENI},
75         {TEX_UNDERBAR,   0x0320, "underbar",        LFUN_ACCENT_UNDERBAR}, // COMBINING MINUS SIGN BELOW or 0x0331 COMBINING MACRON BELOW ?
76
77         {TEX_CEDILLA,    0x0327, "cedilla",         LFUN_ACCENT_CEDILLA},
78         {TEX_UNDERDOT,   0x0323, "underdot",        LFUN_ACCENT_UNDERDOT},
79         {TEX_CIRCUMFLEX, 0x0302, "circumflex",      LFUN_ACCENT_CIRCUMFLEX},
80         {TEX_CIRCLE,     0x030a, "circle",          LFUN_ACCENT_CIRCLE},
81         {TEX_TIE,        0x0361, "tie",             LFUN_ACCENT_TIE},
82         {TEX_BREVE,      0x0306, "breve",           LFUN_ACCENT_BREVE},
83         {TEX_CARON,      0x030c, "caron",           LFUN_ACCENT_CARON},
84         // Don't fix this typo for compatibility reasons!
85         {TEX_HUNGUML,    0x030b, "hugarian_umlaut", LFUN_ACCENT_HUNGARIAN_UMLAUT},
86         {TEX_UMLAUT,     0x0308, "umlaut",          LFUN_ACCENT_UMLAUT},
87         {TEX_DOT,        0x0307, "dot",             LFUN_ACCENT_DOT},
88         {TEX_OGONEK,     0x0328, "ogonek",          LFUN_ACCENT_OGONEK}
89 };
90
91
92 TeXAccent get_accent(FuncCode action)
93 {
94         int i = 0;
95         while (i <= TEX_MAX_ACCENT) {
96                 if (lyx_accent_table[i].action == action)
97                         return lyx_accent_table[i];
98                 ++i;
99         }
100         struct TeXAccent temp = { static_cast<tex_accent>(0), 0,
101                                           0, static_cast<FuncCode>(0)};
102         return temp;
103 }
104
105
106 static docstring const doAccent(docstring const & s, tex_accent accent)
107 {
108         if (s.empty())
109                 return docstring(1, lyx_accent_table[accent].ucs4);
110
111         odocstringstream os;
112         os.put(s[0]);
113         os.put(lyx_accent_table[accent].ucs4);
114         if (s.length() > 1) {
115                 if (accent != TEX_TIE || s.length() > 2)
116                         lyxerr << "Warning: Too many characters given for accent "
117                                << lyx_accent_table[accent].name << '.' << endl;
118                 os << s.substr(1);
119         }
120         return normalize_c(os.str());
121 }
122
123
124 static docstring const doAccent(char_type c, tex_accent accent)
125 {
126         return doAccent(docstring(1, c), accent);
127 }
128
129
130
131 /////////////////////////////////////////////////////////////////////
132 //
133 // Trans
134 //
135 /////////////////////////////////////////////////////////////////////
136
137
138 void Trans::insertException(KmodException & exclist, char_type c,
139         docstring const & data, bool flag, tex_accent accent)
140 {
141         Keyexc p;
142         p.c = c;
143         p.data = data;
144         p.combined = flag;
145         p.accent = accent;
146         exclist.insert(exclist.begin(), p);
147         // or just
148         // exclist.push_back(p);
149 }
150
151
152 void Trans::freeException(KmodException & exclist)
153 {
154         exclist.clear();
155 }
156
157
158 void Trans::freeKeymap()
159 {
160         kmod_list_.clear();
161         keymap_.clear();
162 }
163
164
165 bool Trans::isDefined() const
166 {
167         return !name_.empty();
168 }
169
170
171 enum {
172         KCOMB = 1,
173         KMOD,
174         KMAP,
175         KXMOD
176 };
177
178
179 tex_accent getkeymod(string const &);
180
181
182 void Trans::addDeadkey(tex_accent accent, docstring const & keys)
183 {
184         KmodInfo tmp;
185         tmp.data = keys;
186         tmp.accent = accent;
187         kmod_list_[accent] = tmp;
188
189         for (docstring::size_type i = 0; i < keys.length(); ++i) {
190                 // FIXME This is a hack.
191                 // tmp is no valid UCS4 string, but misused to store the
192                 // accent.
193                 docstring tmp;
194                 tmp += char_type(0);
195                 tmp += char_type(accent);
196                 keymap_[keys[i]] = tmp;
197         }
198 }
199
200
201 int Trans::load(Lexer & lex)
202 {
203         bool error = false;
204
205         while (lex.isOK() && !error) {
206                 switch (lex.lex()) {
207                 case KMOD:
208                 {
209                         LYXERR(Debug::KBMAP, "KMOD:\t" << lex.getString());
210                         if (!lex.next(true))
211                                 return -1;
212
213                         LYXERR(Debug::KBMAP, "key\t`" << lex.getString() << '\'');
214
215                         docstring const keys = lex.getDocString();
216
217                         if (!lex.next(true))
218                                 return -1;
219
220                         LYXERR(Debug::KBMAP, "accent\t`" << lex.getString() << '\'');
221
222                         tex_accent accent = getkeymod(lex.getString());
223
224                         if (accent == TEX_NOACCENT)
225                                 return -1;
226
227 #if 1
228                         // FIXME: This code should be removed...
229                         // But we need to fix up all the kmap files first
230                         // so that this field is not present anymore.
231                         if (!lex.next(true))
232                                 return -1;
233
234                         LYXERR(Debug::KBMAP, "allowed\t`" << lex.getString() << '\'');
235
236                         /* string const allowed = lex.getString(); */
237                         addDeadkey(accent, keys /*, allowed*/);
238 #else
239                         addDeadkey(accent, keys);
240 #endif
241                         break;
242                 }
243                 case KCOMB: {
244                         string str;
245
246                         LYXERR(Debug::KBMAP, "KCOMB:");
247                         if (!lex.next(true))
248                                 return -1;
249
250                         str = lex.getString();
251                         LYXERR(Debug::KBMAP, str);
252
253                         tex_accent accent_1 = getkeymod(str);
254                         if (accent_1 == TEX_NOACCENT)
255                                 return -1;
256
257                         if (!lex.next(true))
258                                 return -1;
259
260                         str = lex.getString();
261                         LYXERR(Debug::KBMAP, str);
262
263                         tex_accent accent_2 = getkeymod(str);
264                         if (accent_2 == TEX_NOACCENT) return -1;
265
266                         map<tex_accent, KmodInfo>::iterator it1 =
267                                 kmod_list_.find(accent_1);
268                         map<tex_accent, KmodInfo>::iterator it2 =
269                                 kmod_list_.find(accent_2);
270                         if (it1 == kmod_list_.end() || it2 == kmod_list_.end())
271                                 return -1;
272
273                         // Find what key accent_2 is on - should
274                         // check about accent_1 also
275                         map<char_type, docstring>::iterator it = keymap_.begin();
276                         map<char_type, docstring>::iterator end = keymap_.end();
277                         for (; it != end; ++it) {
278                                 if (!it->second.empty()
279                                     && it->second[0] == 0
280                                     && it->second[1] == accent_2)
281                                         break;
282                         }
283                         docstring allowed;
284                         if (!lex.next())
285                                 return -1;
286
287                         allowed = lex.getDocString();
288                         LYXERR(Debug::KBMAP, "allowed: " << to_utf8(allowed));
289
290                         insertException(kmod_list_[accent_1].exception_list,
291                                         it->first, allowed, true, accent_2);
292                 }
293                 break;
294                 case KMAP: {
295                         unsigned char key_from;
296
297                         LYXERR(Debug::KBMAP, "KMAP:\t" << lex.getString());
298
299                         if (!lex.next(true))
300                                 return -1;
301
302                         key_from = lex.getString()[0];
303                         LYXERR(Debug::KBMAP, "\t`" << lex.getString() << '\'');
304
305                         if (!lex.next(true))
306                                 return -1;
307
308                         docstring const string_to = lex.getDocString();
309                         keymap_[key_from] = string_to;
310                         LYXERR(Debug::KBMAP, "\t`" << to_utf8(string_to) << '\'');
311                         break;
312                 }
313                 case KXMOD: {
314                         tex_accent accent;
315                         char_type key;
316                         docstring str;
317
318                         LYXERR(Debug::KBMAP, "KXMOD:\t" << lex.getString());
319
320                         if (!lex.next(true))
321                                 return -1;
322
323                         LYXERR(Debug::KBMAP, "\t`" << lex.getString() << '\'');
324                         accent = getkeymod(lex.getString());
325
326                         if (!lex.next(true))
327                                 return -1;
328
329                         LYXERR(Debug::KBMAP, "\t`" << lex.getString() << '\'');
330                         key = lex.getDocString()[0];
331
332                         if (!lex.next(true))
333                                 return -1;
334
335                         LYXERR(Debug::KBMAP, "\t`" << lex.getString() << '\'');
336                         str = lex.getDocString();
337
338                         insertException(kmod_list_[accent].exception_list,
339                                         key, str);
340                         break;
341                 }
342                 case Lexer::LEX_FEOF:
343                         LYXERR(Debug::PARSER, "End of parsing");
344                         break;
345                 default:
346                         lex.printError("ParseKeymapFile: Unknown tag: `$$Token'");
347                         return -1;
348                 }
349         }
350         return 0;
351 }
352
353
354 bool Trans::isAccentDefined(tex_accent accent, KmodInfo & i) const
355 {
356         map<tex_accent, KmodInfo>::const_iterator cit = kmod_list_.find(accent);
357         if (cit == kmod_list_.end())
358                 return false;
359         i = cit->second;
360         return true;
361 }
362
363
364 docstring const Trans::process(char_type c, TransManager & k)
365 {
366         docstring const t = match(c);
367
368         if (t.empty() && c != 0)
369                 return k.normalkey(c);
370
371         if (!t.empty() && t[0] != 0)
372                 return t; //return k.normalkey(c);
373
374         return k.deadkey(c, kmod_list_[static_cast<tex_accent>(t[1])]);
375 }
376
377
378 int Trans::load(string const & language)
379 {
380         LexerKeyword kmapTags[] = {
381                 {"\\kcomb", KCOMB },
382                 { "\\kmap", KMAP },
383                 { "\\kmod", KMOD },
384                 { "\\kxmod", KXMOD }
385         };
386
387         FileName const filename = libFileSearch("kbd", language, "kmap");
388         if (filename.empty())
389                 return -1;
390
391         freeKeymap();
392         Lexer lex(kmapTags);
393         lex.setFile(filename);
394
395         int const res = load(lex);
396
397         if (res == 0)
398                 name_ = language;
399         else
400                 name_.erase();
401
402         return res;
403 }
404
405
406 tex_accent getkeymod(string const & p)
407         /* return modifier - decoded from p and update p */
408 {
409         for (int i = 1; i <= TEX_MAX_ACCENT; ++i) {
410                 LYXERR(Debug::KBMAP, "p = " << p
411                        << ", lyx_accent_table[" << i
412                        << "].name = `" << lyx_accent_table[i].name << '\'');
413
414                 if (lyx_accent_table[i].name
415                      && contains(p, lyx_accent_table[i].name)) {
416                         LYXERR(Debug::KBMAP, "Found it!");
417                         return static_cast<tex_accent>(i);
418                 }
419         }
420         return TEX_NOACCENT;
421 }
422
423
424 /////////////////////////////////////////////////////////////////////
425 //
426 // TransState
427 //
428 /////////////////////////////////////////////////////////////////////
429
430
431 // TransFSMData
432 TransFSMData::TransFSMData() : deadkey_(0), deadkey2_(0), init_state_(0),
433         deadkey_state_(0), combined_state_(0), currentState(0)
434 {
435 }
436
437
438 // TransState
439 char_type const TransState::TOKEN_SEP = 4;
440
441
442 // TransInitState
443 TransInitState::TransInitState()
444 {
445         init_state_ = this;
446 }
447
448
449 docstring const TransInitState::normalkey(char_type c)
450 {
451         docstring res;
452         res = c;
453         return res;
454 }
455
456
457 docstring const TransInitState::deadkey(char_type c, KmodInfo d)
458 {
459         deadkey_ = c;
460         deadkey_info_ = d;
461         currentState = deadkey_state_;
462         return docstring();
463 }
464
465
466 // TransDeadkeyState
467 TransDeadkeyState::TransDeadkeyState()
468 {
469         deadkey_state_ = this;
470 }
471
472
473 docstring const TransDeadkeyState::normalkey(char_type c)
474 {
475         docstring res;
476
477         KmodException::iterator it = deadkey_info_.exception_list.begin();
478         KmodException::iterator end = deadkey_info_.exception_list.end();
479
480         for (; it != end; ++it) {
481                 if (it->c == c) {
482                         res = it->data;
483                         break;
484                 }
485         }
486         if (it == end) {
487                 res = doAccent(c, deadkey_info_.accent);
488         }
489         currentState = init_state_;
490         return res;
491 }
492
493
494 docstring const TransDeadkeyState::deadkey(char_type c, KmodInfo d)
495 {
496         docstring res;
497
498         // Check if the same deadkey was typed twice
499         if (deadkey_ == c) {
500                 res = deadkey_;
501                 deadkey_ = 0;
502                 deadkey_info_.accent = TEX_NOACCENT;
503                 currentState = init_state_;
504                 return res;
505         }
506
507         // Check if it is a combination or an exception
508         KmodException::const_iterator cit = deadkey_info_.exception_list.begin();
509         KmodException::const_iterator end = deadkey_info_.exception_list.end();
510         for (; cit != end; ++cit) {
511                 if (cit->combined == true && cit->accent == d.accent) {
512                         deadkey2_ = c;
513                         deadkey2_info_ = d;
514                         comb_info_ = (*cit);
515                         currentState = combined_state_;
516                         return docstring();
517                 }
518                 if (cit->c == c) {
519                         res = cit->data;
520                         deadkey_ = 0;
521                         deadkey_info_.accent = TEX_NOACCENT;
522                         currentState = init_state_;
523                         return res;
524                 }
525         }
526
527         // Not a combination or an exception.
528         // Output deadkey1 and keep deadkey2
529
530         if (deadkey_!= 0)
531                 res = deadkey_;
532         deadkey_ = c;
533         deadkey_info_ = d;
534         currentState = deadkey_state_;
535         return res;
536 }
537
538
539 TransCombinedState::TransCombinedState()
540 {
541         combined_state_ = this;
542 }
543
544
545 docstring const TransCombinedState::normalkey(char_type c)
546 {
547         docstring const temp = doAccent(c, deadkey2_info_.accent);
548         docstring const res = doAccent(temp, deadkey_info_.accent);
549         currentState = init_state_;
550         return res;
551 }
552
553
554 docstring const TransCombinedState::deadkey(char_type c, KmodInfo d)
555 {
556         // Third key in a row. Output the first one and
557         // reenter with shifted deadkeys
558         docstring res;
559         if (deadkey_ != 0)
560                 res = deadkey_;
561         res += TOKEN_SEP;
562         deadkey_ = deadkey2_;
563         deadkey_info_ = deadkey2_info_;
564         res += deadkey_state_->deadkey(c, d);
565         return res;
566 }
567
568
569 // TransFSM
570 TransFSM::TransFSM()
571         : TransFSMData(), TransInitState(), TransDeadkeyState(), TransCombinedState()
572 {
573         currentState = init_state_;
574 }
575
576
577 // TransManager
578
579 // Initialize static member.
580 Trans TransManager::default_;
581
582
583 TransManager::TransManager()
584         : active_(&default_)
585 {}
586
587
588 int TransManager::setPrimary(string const & language)
589 {
590         if (t1_.getName() == language)
591                 return 0;
592
593         return t1_.load(language);
594 }
595
596
597 int TransManager::setSecondary(string const & language)
598 {
599         if (t2_.getName() == language)
600                 return 0;
601
602         return t2_.load(language);
603 }
604
605
606 void TransManager::enablePrimary()
607 {
608         if (t1_.isDefined())
609                 active_ = &t1_;
610
611         LYXERR(Debug::KBMAP, "Enabling primary keymap");
612 }
613
614
615 void TransManager::enableSecondary()
616 {
617         if (t2_.isDefined())
618                 active_ = &t2_;
619         LYXERR(Debug::KBMAP, "Enabling secondary keymap");
620 }
621
622
623 void TransManager::disableKeymap()
624 {
625         active_ = &default_;
626         LYXERR(Debug::KBMAP, "Disabling keymap");
627 }
628
629
630 void  TransManager::translateAndInsert(char_type c, Text * text, Cursor & cur)
631 {
632         docstring res = active_->process(c, *this);
633
634         // Process with tokens
635         docstring temp;
636
637         while (res.length() > 0) {
638                 res = split(res, temp, TransState::TOKEN_SEP);
639                 insert(temp, text, cur);
640         }
641 }
642
643
644 void TransManager::insert(docstring const & str, Text * text, Cursor & cur)
645 {
646         for (size_t i = 0, n = str.size(); i != n; ++i)
647                 text->insertChar(cur, str[i]);
648 }
649
650
651 void TransManager::deadkey(char_type c, tex_accent accent, Text * t, Cursor & cur)
652 {
653         if (c == 0 && active_ != &default_) {
654                 // A deadkey was pressed that cannot be printed
655                 // or a accent command was typed in the minibuffer
656                 KmodInfo i;
657                 if (active_->isAccentDefined(accent, i) == true) {
658                         docstring const res = trans_fsm_
659                                 .currentState->deadkey(c, i);
660                         insert(res, t, cur);
661                         return;
662                 }
663         }
664
665         if (active_ == &default_ || c == 0) {
666                 KmodInfo i;
667                 i.accent = accent;
668                 i.data.erase();
669                 docstring res = trans_fsm_.currentState->deadkey(c, i);
670                 insert(res, t, cur);
671         } else {
672                 // Go through the translation
673                 translateAndInsert(c, t, cur);
674         }
675 }
676
677
678 } // namespace lyx