]> git.lyx.org Git - lyx.git/blob - src/insets/InsetQuotes.cpp
cc3e3e051e1475b62f558d4727e63c177e97e665
[lyx.git] / src / insets / InsetQuotes.cpp
1 /**
2  * \file InsetQuotes.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jean-Marc Lasgouttes
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "InsetQuotes.h"
14
15 #include "Buffer.h"
16 #include "BufferParams.h"
17 #include "BufferView.h"
18 #include "Cursor.h"
19 #include "Dimension.h"
20 #include "Font.h"
21 #include "FuncStatus.h"
22 #include "FuncRequest.h"
23 #include "Language.h"
24 #include "LaTeXFeatures.h"
25 #include "Lexer.h"
26 #include "LyXRC.h"
27 #include "MetricsInfo.h"
28 #include "OutputParams.h"
29 #include "output_xhtml.h"
30 #include "Paragraph.h"
31 #include "ParIterator.h"
32 #include "texstream.h"
33
34 #include "frontends/FontMetrics.h"
35 #include "frontends/Painter.h"
36
37 #include "support/debug.h"
38 #include "support/docstring.h"
39 #include "support/docstream.h"
40 #include "support/lstrings.h"
41
42 using namespace std;
43 using namespace lyx::support;
44
45 namespace lyx {
46
47 namespace {
48
49 /* codes used to read/write quotes to LyX files
50  * e    ``english''
51  * s    ''swedish''
52  * g    ,,german``
53  * p    ,,polish''
54  * f    <<french>>
55  * a    >>danish<<
56  * q    "plain"
57  */
58
59 char const * const style_char = "esgpfaq";
60 char const * const side_char = "lr" ;
61 char const * const level_char = "sd";
62
63 // List of known quote chars
64 char const * const quote_char = ",'`<>\"";
65
66 // Unicode characters needed by each quote type
67 char_type const display_quote_char[2][6] = {
68         { 0x201a, 0x2019, 0x2018, 0x2039, 0x203a, 0x0027},
69         { 0x201e, 0x201d, 0x201c, 0x00ab, 0x00bb, 0x0022}
70 };
71
72 // Index of chars used for the quote. Index is [side, style]
73 int quote_index[2][7] = {
74         { 2, 1, 0, 0, 3, 4, 5 },  // { ` ' , , < > \" }
75         { 1, 1, 2, 1, 4, 3, 5 }   // { ' ' ` ' > < \" }
76 };
77
78 // Corresponding LaTeX code, for double and single quotes.
79 char const * const latex_quote_t1[2][6] = {
80         { "\\quotesinglbase",  "'", "`",
81     "\\guilsinglleft", "\\guilsinglright", "\\textquotesingle" },
82   { ",,", "''", "``", "<<", ">>", "\\textquotedbl" }
83 };
84
85 char const * const latex_quote_ot1[2][6] = {
86         { "\\quotesinglbase",  "'", "`",
87     "\\guilsinglleft", "\\guilsinglright", "\\textquotesingle" },
88   { "\\quotedblbase", "''", "``",
89     "\\guillemotleft", "\\guillemotright", "\\textquotedbl" }
90 };
91
92 char const * const latex_quote_noligatures[2][6] = {
93         { "\\quotesinglbase",  "\\textquoteleft", "\\textquoteright",
94     "\\guilsinglleft", "\\guilsinglright", "\\textquotesingle" },
95   { "\\quotedblbase", "\\textquotedblleft", "\\textquotedblright",
96     "\\guillemotleft", "\\guillemotright", "\\textquotedbl" }
97 };
98
99 char const * const latex_quote_babel[2][6] = {
100         { "\\glq",  "'", "`", "\\flq", "\\frq", "\\textquotesingle" },
101   { "\\glqq", "''", "``", "\\flqq", "\\frqq", "\\textquotedbl" }
102 };
103
104 char const * const html_quote[2][6] = {
105         { "&sbquo;",  "&rsquo;", "&lsquo;",
106           "&lsaquo;", "&rsaquo;", "&#x27;" },
107   { "&bdquo;", "&rdquo;", "&ldquo;", "&laquo;", "&raquo;", "&quot;" }
108 };
109
110 } // namespace anon
111
112
113 InsetQuotes::InsetQuotes(Buffer * buf, string const & str) : Inset(buf)
114 {
115         parseString(str);
116 }
117
118
119 InsetQuotes::InsetQuotes(Buffer * buf, char_type c, QuoteLevel level,
120                          string const & side, string const & style)
121         : Inset(buf), level_(level), pass_thru_(false)
122 {
123         if (buf) {
124                 style_ = style.empty() ? buf->params().quotes_style : getStyle(style);
125                 fontenc_ = (buf->params().fontenc == "global")
126                         ? lyxrc.fontenc : buf->params().fontenc;
127         } else {
128                 style_ = style.empty() ? EnglishQuotes : getStyle(style);
129                 fontenc_ = lyxrc.fontenc;
130         }
131
132         if (side == "left")
133                 side_ = LeftQuote;
134         else if (side == "right")
135                 side_ = RightQuote;
136         else
137                 setSide(c);
138 }
139
140
141 docstring InsetQuotes::layoutName() const
142 {
143         return from_ascii("Quotes");
144 }
145
146
147 void InsetQuotes::setSide(char_type c)
148 {
149         // Decide whether left or right
150         switch (c) {
151         case ' ':
152         case '(':
153         case '[':
154                 side_ = LeftQuote;   // left quote
155                 break;
156         default:
157                 side_ = RightQuote;  // right quote
158         }
159 }
160
161
162 void InsetQuotes::parseString(string const & s, bool const allow_wildcards)
163 {
164         string str = s;
165         if (str.length() != 3) {
166                 lyxerr << "ERROR (InsetQuotes::InsetQuotes):"
167                         " bad string length." << endl;
168                 str = "eld";
169         }
170
171         int i;
172
173         // '.' wildcard means: keep current stylee
174         if (!allow_wildcards || str[0] != '.') {
175                 for (i = 0; i < 7; ++i) {
176                         if (str[0] == style_char[i]) {
177                                 style_ = QuoteStyle(i);
178                                 break;
179                         }
180                 }
181                 if (i >= 7) {
182                         lyxerr << "ERROR (InsetQuotes::InsetQuotes):"
183                                 " bad style specification." << endl;
184                         style_ = EnglishQuotes;
185                 }
186         }
187
188         // '.' wildcard means: keep current side
189         if (!allow_wildcards || str[1] != '.') {
190                 for (i = 0; i < 2; ++i) {
191                         if (str[1] == side_char[i]) {
192                                 side_ = QuoteSide(i);
193                                 break;
194                         }
195                 }
196                 if (i >= 2) {
197                         lyxerr << "ERROR (InsetQuotes::InsetQuotes):"
198                                 " bad side specification." << endl;
199                         side_ = LeftQuote;
200                 }
201         }
202
203         // '.' wildcard means: keep current level
204         if (!allow_wildcards || str[2] != '.') {
205                 for (i = 0; i < 2; ++i) {
206                         if (str[2] == level_char[i]) {
207                                 level_ = QuoteLevel(i);
208                                 break;
209                         }
210                 }
211                 if (i >= 2) {
212                         lyxerr << "ERROR (InsetQuotes::InsetQuotes):"
213                                 " bad level specification." << endl;
214                         level_ = DoubleQuotes;
215                 }
216         }
217 }
218
219
220 InsetQuotes::QuoteStyle InsetQuotes::getStyle(string const & s)
221 {
222         QuoteStyle qs = EnglishQuotes;
223         
224         if (s == "english")
225                 qs = EnglishQuotes;
226         else if (s == "swedish")
227                 qs = SwedishQuotes;
228         else if (s == "german")
229                 qs = GermanQuotes;
230         else if (s == "polish")
231                 qs = PolishQuotes;
232         else if (s == "french")
233                 qs = FrenchQuotes;
234         else if (s == "danish")
235                 qs = DanishQuotes;
236         else if (s == "plain")
237                 qs = PlainQuotes;
238
239         return qs;
240 }
241
242
243 map<string, docstring> InsetQuotes::getTypes() const
244 {
245         map<string, docstring> res;
246
247         int sty, sid, lev;
248         QuoteStyle style;
249         QuoteSide side;
250         QuoteLevel level;
251         string type;
252
253         // get all quote types
254         for (sty = 0; sty < 7; ++sty) {
255                 style = QuoteStyle(sty);
256                 for (sid = 0; sid < 2; ++sid) {
257                         side = QuoteSide(sid);
258                         for (lev = 0; lev < 2; ++lev) {
259                                 type += style_char[style];
260                                 type += side_char[sid];
261                                 level = QuoteLevel(lev);
262                                 type += level_char[lev];
263                                 res[type] = docstring(1, display_quote_char[level][quote_index[side][style]]);
264                                 type.clear();
265                         }
266                 }
267         }
268         return res;
269 }
270
271
272 docstring InsetQuotes::displayString() const
273 {
274         // In PassThru, we use straight quotes
275         if (pass_thru_)
276                 return (level_ == DoubleQuotes) ? from_ascii("\"") : from_ascii("'");
277
278         int const index = quote_index[side_][style_];
279         docstring retdisp = docstring(1, display_quote_char[level_][index]);
280
281         // in French, thin spaces are added inside double guillemets
282         if (prefixIs(context_lang_, "fr")
283             && level_ == DoubleQuotes && style_ == FrenchQuotes) {
284                 // THIN SPACE (U+2009)
285                 char_type const thin_space = 0x2009;
286                 if (side_ == LeftQuote)
287                         retdisp += thin_space;
288                 else
289                         retdisp = thin_space + retdisp;
290         }
291
292         return retdisp;
293 }
294
295
296 void InsetQuotes::metrics(MetricsInfo & mi, Dimension & dim) const
297 {
298         FontInfo & font = mi.base.font;
299         frontend::FontMetrics const & fm = theFontMetrics(font);
300         dim.asc = fm.maxAscent();
301         dim.des = fm.maxDescent();
302         dim.wid = fm.width(displayString());
303 }
304
305
306 void InsetQuotes::draw(PainterInfo & pi, int x, int y) const
307 {
308         FontInfo font = pi.base.font;
309         font.setPaintColor(pi.textColor(font.realColor()));
310         pi.pain.text(x, y, displayString(), font);
311 }
312
313
314 string InsetQuotes::getType() const
315 {
316         string text;
317         text += style_char[style_];
318         text += side_char[side_];
319         text += level_char[level_];
320         return text;
321 }
322
323
324 void InsetQuotes::write(ostream & os) const
325 {
326         os << "Quotes " << getType();
327 }
328
329
330 void InsetQuotes::read(Lexer & lex)
331 {
332         lex.setContext("InsetQuotes::read");
333         lex.next();
334         parseString(lex.getString());
335         lex >> "\\end_inset";
336 }
337
338
339 void InsetQuotes::doDispatch(Cursor & cur, FuncRequest & cmd)
340 {
341         switch (cmd.action()) {
342         case LFUN_INSET_MODIFY: {
343                 string const first_arg = cmd.getArg(0);
344                 bool const change_type = first_arg == "changetype";
345                 if (!change_type) {
346                         // not for us
347                         // this will not be handled higher up
348                         cur.undispatched();
349                         return;
350                 }
351                 cur.recordUndoInset(this);
352                 parseString(cmd.getArg(1), true);
353                 cur.buffer()->updateBuffer();
354                 break;
355         }
356         default:
357                 Inset::doDispatch(cur, cmd);
358                 break;
359         }
360 }
361
362
363 bool InsetQuotes::getStatus(Cursor & cur, FuncRequest const & cmd,
364                 FuncStatus & flag) const
365 {
366         switch (cmd.action()) {
367
368         case LFUN_INSET_MODIFY: {
369                 string const first_arg = cmd.getArg(0);
370                 if (first_arg == "changetype") {
371                         string const type = cmd.getArg(1);
372                         flag.setOnOff(type == getType());
373                         flag.setEnabled(!pass_thru_);
374                         return true;
375                 }
376                 return Inset::getStatus(cur, cmd, flag);
377         }
378
379         default:
380                 return Inset::getStatus(cur, cmd, flag);
381         }
382 }
383
384
385 void InsetQuotes::latex(otexstream & os, OutputParams const & runparams) const
386 {
387         const int quoteind = quote_index[side_][style_];
388         docstring qstr;
389
390         // In pass-thru context, we output plain quotes
391         if (runparams.pass_thru)
392                 qstr = (level_ == DoubleQuotes) ? from_ascii("\"") : from_ascii("'");
393         else if (style_ == PlainQuotes && runparams.isFullUnicode()) {
394                 // For XeTeX and LuaTeX,we need to disable mapping to get straight
395                 // quotes. We define our own commands that do this
396                 qstr = (level_ == DoubleQuotes) ?
397                         from_ascii("\\textquotedblplain") : from_ascii("\\textquotesingleplain");
398         }
399         else if (runparams.use_polyglossia) {
400                 // For polyglossia, we directly output the respective unicode chars 
401                 // (spacing and kerning is then handled respectively)
402                 qstr = docstring(1, display_quote_char[level_][quoteind]);
403         }
404         else if (style_ == FrenchQuotes && level_ == DoubleQuotes
405                  && prefixIs(runparams.local_font->language()->code(), "fr")) {
406                 // Specific guillemets of French babel
407                 // including correct French spacing
408                 if (side_ == LeftQuote)
409                         qstr = from_ascii("\\og");
410                 else
411                         qstr = from_ascii("\\fg");
412         } else if (fontenc_ == "T1"
413                    && !runparams.local_font->language()->internalFontEncoding()) {
414                 // Quotation marks for T1 font encoding
415                 // (using ligatures)
416                 qstr = from_ascii(latex_quote_t1[level_][quoteind]);
417         } else if (runparams.local_font->language()->internalFontEncoding()) {
418                 // Quotation marks for internal font encodings
419                 // (ligatures not featured)
420                 qstr = from_ascii(latex_quote_noligatures[level_][quoteind]);
421 #ifdef DO_USE_DEFAULT_LANGUAGE
422         } else if (doclang == "default") {
423 #else
424         } else if (!runparams.use_babel || runparams.isFullUnicode()) {
425 #endif
426                 // Standard quotation mark macros
427                 // These are also used by babel
428                 // without fontenc (XeTeX/LuaTeX)
429                 qstr = from_ascii(latex_quote_ot1[level_][quoteind]);
430         } else {
431                 // Babel shorthand quotation marks (for T1/OT1)
432                 qstr = from_ascii(latex_quote_babel[level_][quoteind]);
433         }
434
435         if (!runparams.pass_thru) {
436                 // Guard against unwanted ligatures with preceding text
437                 char_type const lastchar = os.lastChar();
438                 // !` ?` => !{}` ?{}`
439                 if (prefixIs(qstr, from_ascii("`"))
440                     && (lastchar == '!' || lastchar == '?'))
441                         os << "{}";
442                 // ``` ''' ,,, <<< >>>
443                 // => `{}`` '{}'' ,{},, <{}<< >{}>>
444                 if (contains(from_ascii(",'`<>"), lastchar)
445                     && prefixIs(qstr, lastchar))
446                         os << "{}";
447         }
448
449         os << qstr;
450
451         if (prefixIs(qstr, from_ascii("\\")))
452                 // properly terminate the command depending on the context
453                 os << termcmd;
454 }
455
456
457 int InsetQuotes::plaintext(odocstringstream & os, 
458         OutputParams const &, size_t) const
459 {
460         docstring const str = displayString();
461         os << str;
462         return str.size();
463 }
464
465
466 docstring InsetQuotes::getQuoteEntity() const {
467         const int quoteind = quote_index[side_][style_];
468         docstring res = from_ascii(html_quote[level_][quoteind]);
469         // in French, thin spaces are added inside double guillemets
470         if (prefixIs(context_lang_, "fr")
471             && level_ == DoubleQuotes && style_ == FrenchQuotes) {
472                 // THIN SPACE (U+2009)
473                 docstring const thin_space = from_ascii("&#x2009;");
474                 if (side_ == LeftQuote)
475                         res += thin_space;
476                 else
477                         res = thin_space + res;
478         }
479         return res;
480 }
481
482
483 int InsetQuotes::docbook(odocstream & os, OutputParams const &) const
484 {
485         os << getQuoteEntity();
486         return 0;
487 }
488
489
490 docstring InsetQuotes::xhtml(XHTMLStream & xs, OutputParams const &) const
491 {
492         xs << XHTMLStream::ESCAPE_NONE << getQuoteEntity();
493         return docstring();
494 }
495
496
497 void InsetQuotes::toString(odocstream & os) const
498 {
499         os << displayString();
500 }
501
502
503 void InsetQuotes::forOutliner(docstring & os, size_t const, bool const) const
504 {
505         os += displayString();
506 }
507
508
509 void InsetQuotes::updateBuffer(ParIterator const & it, UpdateType /* utype*/)
510 {
511         BufferParams const & bp = buffer().masterBuffer()->params();
512         pass_thru_ = it.paragraph().isPassThru();
513         context_lang_ = it.paragraph().getFontSettings(bp, it.pos()).language()->code();
514         fontenc_ = (bp.fontenc == "global") ? lyxrc.fontenc : bp.fontenc;
515 }
516
517
518 void InsetQuotes::validate(LaTeXFeatures & features) const
519 {
520         char type = quote_char[quote_index[side_][style_]];
521
522 #ifdef DO_USE_DEFAULT_LANGUAGE
523         if (features.bufferParams().language->lang() == "default"
524 #else
525         if (!features.useBabel()
526 #endif
527             && !features.runparams().isFullUnicode() && fontenc_ != "T1") {
528                 if (level_ == SingleQuotes)
529                         switch (type) {
530                         case ',':
531                                 features.require("quotesinglbase");
532                                 break;
533                         case '<':
534                                 features.require("guilsinglleft");
535                                 break;
536                         case '>':
537                                 features.require("guilsinglright");
538                                 break;
539                         default:
540                                 break;
541                         }
542                 else
543                         switch (type) {
544                         case ',':
545                                 features.require("quotedblbase");
546                                 break;
547                         case '<':
548                                 features.require("guillemotleft");
549                                 break;
550                         case '>':
551                                 features.require("guillemotright");
552                                 break;
553                         default:
554                                 break;
555                         }
556         }
557         if (type == '"') {
558                 switch (level_) {
559                 case SingleQuotes: {
560                         if (features.runparams().isFullUnicode())
561                                 features.require("textquotesinglep");
562                         else
563                                 features.require("textcomp");
564                         break;
565                 }
566                 case DoubleQuotes: {
567                         if (features.runparams().isFullUnicode())
568                                 features.require("textquotedblp");
569                         else if (fontenc_ != "T1")
570                                 features.require("textquotedbl");
571                         break;
572                 default:
573                         break;
574                 }
575                 }
576         }
577 }
578
579
580 string InsetQuotes::contextMenuName() const
581 {
582         return "context-quote";
583 }
584
585 } // namespace lyx