]> git.lyx.org Git - lyx.git/blob - src/insets/InsetText.cpp
709ae04b4f16b272f8df511466723dbd06fd00a3
[lyx.git] / src / insets / InsetText.cpp
1 /**
2  * \file InsetText.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Vigna
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "InsetText.h"
14
15 #include "insets/InsetOptArg.h"
16
17 #include "buffer_funcs.h"
18 #include "Buffer.h"
19 #include "BufferParams.h"
20 #include "BufferView.h"
21 #include "CompletionList.h"
22 #include "CoordCache.h"
23 #include "Cursor.h"
24 #include "CutAndPaste.h"
25 #include "DispatchResult.h"
26 #include "ErrorList.h"
27 #include "FuncRequest.h"
28 #include "FuncStatus.h"
29 #include "InsetCaption.h"
30 #include "InsetList.h"
31 #include "Intl.h"
32 #include "Language.h"
33 #include "Lexer.h"
34 #include "lyxfind.h"
35 #include "LyXRC.h"
36 #include "MetricsInfo.h"
37 #include "output_docbook.h"
38 #include "output_latex.h"
39 #include "output_xhtml.h"
40 #include "OutputParams.h"
41 #include "output_plaintext.h"
42 #include "paragraph_funcs.h"
43 #include "Paragraph.h"
44 #include "ParagraphParameters.h"
45 #include "ParIterator.h"
46 #include "Row.h"
47 #include "sgml.h"
48 #include "TexRow.h"
49 #include "TextClass.h"
50 #include "Text.h"
51 #include "TextMetrics.h"
52 #include "TocBackend.h"
53
54 #include "frontends/alert.h"
55 #include "frontends/Painter.h"
56
57 #include "support/debug.h"
58 #include "support/gettext.h"
59 #include "support/lstrings.h"
60
61 #include <boost/bind.hpp>
62 #include "support/lassert.h"
63
64 using namespace std;
65 using namespace lyx::support;
66
67 using boost::bind;
68 using boost::ref;
69
70 namespace lyx {
71
72 using graphics::PreviewLoader;
73
74
75 /////////////////////////////////////////////////////////////////////
76
77 InsetText::InsetText(Buffer const & buf, UsePlain type)
78         : drawFrame_(false), frame_color_(Color_insetframe)
79 {
80         setBuffer(const_cast<Buffer &>(buf));
81         initParagraphs(type);
82 }
83
84
85 InsetText::InsetText(InsetText const & in)
86         : Inset(in), text_()
87 {
88         text_.autoBreakRows_ = in.text_.autoBreakRows_;
89         drawFrame_ = in.drawFrame_;
90         frame_color_ = in.frame_color_;
91         text_.paragraphs() = in.text_.paragraphs();
92         setParagraphOwner();
93 }
94
95
96 void InsetText::setBuffer(Buffer & buf)
97 {
98         ParagraphList::iterator end = paragraphs().end();
99         for (ParagraphList::iterator it = paragraphs().begin(); it != end; ++it)
100                 it->setBuffer(buf);
101         Inset::setBuffer(buf);
102 }
103
104
105 void InsetText::initParagraphs(UsePlain type)
106 {
107         LASSERT(paragraphs().empty(), /**/);
108         paragraphs().push_back(Paragraph());
109         Paragraph & ourpar = paragraphs().back();
110         ourpar.setInsetOwner(this);
111         DocumentClass const & dc = buffer_->params().documentClass();
112         if (type == DefaultLayout)
113                 ourpar.setDefaultLayout(dc);
114         else
115                 ourpar.setPlainLayout(dc);
116 }
117
118
119 void InsetText::setParagraphOwner()
120 {
121         for_each(paragraphs().begin(), paragraphs().end(),
122                  bind(&Paragraph::setInsetOwner, _1, this));
123 }
124
125
126 void InsetText::clear()
127 {
128         ParagraphList & pars = paragraphs();
129         LASSERT(!pars.empty(), /**/);
130
131         // This is a gross hack...
132         Layout const & old_layout = pars.begin()->layout();
133
134         pars.clear();
135         pars.push_back(Paragraph());
136         pars.begin()->setInsetOwner(this);
137         pars.begin()->setLayout(old_layout);
138 }
139
140
141 Dimension const InsetText::dimension(BufferView const & bv) const
142 {
143         TextMetrics const & tm = bv.textMetrics(&text_);
144         Dimension dim = tm.dimension();
145         dim.wid += 2 * TEXT_TO_INSET_OFFSET;
146         dim.des += TEXT_TO_INSET_OFFSET;
147         dim.asc += TEXT_TO_INSET_OFFSET;
148         return dim;
149 }
150
151
152 void InsetText::write(ostream & os) const
153 {
154         os << "Text\n";
155         text_.write(buffer(), os);
156 }
157
158
159 void InsetText::read(Lexer & lex)
160 {
161         clear();
162
163         // delete the initial paragraph
164         Paragraph oldpar = *paragraphs().begin();
165         paragraphs().clear();
166         ErrorList errorList;
167         lex.setContext("InsetText::read");
168         bool res = text_.read(buffer(), lex, errorList, this);
169
170         if (!res)
171                 lex.printError("Missing \\end_inset at this point. ");
172
173         // sanity check
174         // ensure we have at least one paragraph.
175         if (paragraphs().empty())
176                 paragraphs().push_back(oldpar);
177         // Force default font, if so requested
178         // This avoids paragraphs in buffer language that would have a
179         // foreign language after a document language change, and it ensures
180         // that all new text in ERT and similar gets the "latex" language,
181         // since new text inherits the language from the last position of the
182         // existing text.  As a side effect this makes us also robust against
183         // bugs in LyX that might lead to font changes in ERT in .lyx files.
184         fixParagraphsFont();
185 }
186
187
188 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
189 {
190         TextMetrics & tm = mi.base.bv->textMetrics(&text_);
191
192         //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
193
194         // Hand font through to contained lyxtext:
195         tm.font_.fontInfo() = mi.base.font;
196         mi.base.textwidth -= 2 * TEXT_TO_INSET_OFFSET;
197
198         // This can happen when a layout has a left and right margin,
199         // and the view is made very narrow. We can't do better than 
200         // to draw it partly out of view (bug 5890).
201         if (mi.base.textwidth < 1)
202                 mi.base.textwidth = 1;
203
204         if (hasFixedWidth())
205                 tm.metrics(mi, dim, mi.base.textwidth);
206         else
207                 tm.metrics(mi, dim);
208         mi.base.textwidth += 2 * TEXT_TO_INSET_OFFSET;
209         dim.asc += TEXT_TO_INSET_OFFSET;
210         dim.des += TEXT_TO_INSET_OFFSET;
211         dim.wid += 2 * TEXT_TO_INSET_OFFSET;
212 }
213
214
215 void InsetText::draw(PainterInfo & pi, int x, int y) const
216 {
217         TextMetrics & tm = pi.base.bv->textMetrics(&text_);
218
219         if (drawFrame_ || pi.full_repaint) {
220                 int const w = tm.width() + TEXT_TO_INSET_OFFSET;
221                 int const yframe = y - TEXT_TO_INSET_OFFSET - tm.ascent();
222                 int const h = tm.height() + 2 * TEXT_TO_INSET_OFFSET;
223                 int const xframe = x + TEXT_TO_INSET_OFFSET / 2;
224                 if (pi.full_repaint)
225                         pi.pain.fillRectangle(xframe, yframe, w, h,
226                                 pi.backgroundColor(this));
227
228                 if (drawFrame_)
229                         pi.pain.rectangle(xframe, yframe, w, h, frameColor());
230         }
231         ColorCode const old_color = pi.background_color;
232         pi.background_color = pi.backgroundColor(this, false);
233
234         tm.draw(pi, x + TEXT_TO_INSET_OFFSET, y);
235
236         pi.background_color = old_color;
237 }
238
239
240 docstring InsetText::editMessage() const
241 {
242         return _("Opened Text Inset");
243 }
244
245
246 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
247 {
248         pit_type const pit = front ? 0 : paragraphs().size() - 1;
249         pos_type pos = front ? 0 : paragraphs().back().size();
250
251         // if visual information is not to be ignored, move to extreme right/left
252         if (entry_from != ENTRY_DIRECTION_IGNORE) {
253                 Cursor temp_cur = cur;
254                 temp_cur.pit() = pit;
255                 temp_cur.pos() = pos;
256                 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
257                 pos = temp_cur.pos();
258         }
259
260         text_.setCursor(cur.top(), pit, pos);
261         cur.clearSelection();
262         cur.finishUndo();
263 }
264
265
266 Inset * InsetText::editXY(Cursor & cur, int x, int y)
267 {
268         return cur.bv().textMetrics(&text_).editXY(cur, x, y);
269 }
270
271
272 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
273 {
274         LYXERR(Debug::ACTION, "InsetText::doDispatch()"
275                 << " [ cmd.action = " << cmd.action << ']');
276
277         // FIXME this use of forceLTR is dubious
278         // introduced in http://www.lyx.org/trac/changeset/21285
279         if (getLayout().isForceLtr()) {
280                 // Force any new text to latex_language FIXME: This
281                 // should only be necessary in constructor, but new
282                 // paragraphs that are created by pressing enter at
283                 // the start of an existing paragraph get the buffer
284                 // language and not latex_language, so we take this
285                 // brute force approach.
286                 cur.current_font.setLanguage(latex_language);
287                 cur.real_current_font.setLanguage(latex_language);
288         }
289
290         switch (cmd.action) {
291         case LFUN_PASTE:
292         case LFUN_CLIPBOARD_PASTE:
293         case LFUN_SELECTION_PASTE:
294         case LFUN_PRIMARY_SELECTION_PASTE:
295                 text_.dispatch(cur, cmd);
296                 // If we we can only store plain text, we must reset all
297                 // attributes.
298                 // FIXME: Change only the pasted paragraphs
299                 fixParagraphsFont();
300                 break;
301         default:
302                 text_.dispatch(cur, cmd);
303         }
304         
305         if (!cur.result().dispatched())
306                 Inset::doDispatch(cur, cmd);
307 }
308
309
310 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
311         FuncStatus & status) const
312 {
313         switch (cmd.action) {
314         case LFUN_LAYOUT:
315                 status.setEnabled(!forcePlainLayout());
316                 return true;
317
318         case LFUN_LAYOUT_PARAGRAPH:
319         case LFUN_PARAGRAPH_PARAMS:
320         case LFUN_PARAGRAPH_PARAMS_APPLY:
321         case LFUN_PARAGRAPH_SPACING:
322         case LFUN_PARAGRAPH_UPDATE:
323                 status.setEnabled(allowParagraphCustomization());
324                 return true;
325         default:
326                 // Dispatch only to text_ if the cursor is inside
327                 // the text_. It is not for context menus (bug 5797).
328                 bool ret = false;
329                 if (cur.text() == &text_)
330                         ret = text_.getStatus(cur, cmd, status);
331                 
332                 if (!ret)
333                         ret = Inset::getStatus(cur, cmd, status);
334                 return ret;
335         }
336 }
337
338
339 void InsetText::fixParagraphsFont()
340 {
341         Font font(inherit_font, buffer().params().language);
342         if (getLayout().isForceLtr())
343                 font.setLanguage(latex_language);
344         if (getLayout().isPassThru()) {
345                 ParagraphList::iterator par = paragraphs().begin();
346                 ParagraphList::iterator const end = paragraphs().end();
347                 while (par != end) {
348                         par->resetFonts(font);
349                         par->params().clear();
350                         ++par;
351                 }
352         }
353 }
354
355
356 void InsetText::setChange(Change const & change)
357 {
358         ParagraphList::iterator pit = paragraphs().begin();
359         ParagraphList::iterator end = paragraphs().end();
360         for (; pit != end; ++pit) {
361                 pit->setChange(change);
362         }
363 }
364
365
366 void InsetText::acceptChanges()
367 {
368         text_.acceptChanges(buffer().params());
369 }
370
371
372 void InsetText::rejectChanges()
373 {
374         text_.rejectChanges(buffer().params());
375 }
376
377
378 int InsetText::latex(odocstream & os, OutputParams const & runparams) const
379 {
380         TexRow texrow;
381         latexParagraphs(buffer(), text_, os, texrow, runparams);
382         return texrow.rows();
383 }
384
385
386 int InsetText::plaintext(odocstream & os, OutputParams const & runparams) const
387 {
388         ParagraphList::const_iterator beg = paragraphs().begin();
389         ParagraphList::const_iterator end = paragraphs().end();
390         ParagraphList::const_iterator it = beg;
391         bool ref_printed = false;
392         int len = 0;
393         for (; it != end; ++it) {
394                 if (it != beg) {
395                         os << '\n';
396                         if (runparams.linelen > 0)
397                                 os << '\n';
398                 }
399                 odocstringstream oss;
400                 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed);
401                 docstring const str = oss.str();
402                 os << str;
403                 // FIXME: len is not computed fully correctly; in principle,
404                 // we have to count the characters after the last '\n'
405                 len = str.size();
406         }
407
408         return len;
409 }
410
411
412 int InsetText::docbook(odocstream & os, OutputParams const & runparams) const
413 {
414         docbookParagraphs(paragraphs(), buffer(), os, runparams);
415         return 0;
416 }
417
418
419 docstring InsetText::xhtml(odocstream & os, OutputParams const & runparams) const
420 {
421         xhtmlParagraphs(paragraphs(), buffer(), os, runparams);
422         return docstring();
423 }
424
425
426 void InsetText::validate(LaTeXFeatures & features) const
427 {
428         for_each(paragraphs().begin(), paragraphs().end(),
429                  bind(&Paragraph::validate, _1, ref(features)));
430 }
431
432
433 void InsetText::cursorPos(BufferView const & bv,
434                 CursorSlice const & sl, bool boundary, int & x, int & y) const
435 {
436         x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
437         y = bv.textMetrics(&text_).cursorY(sl, boundary);
438 }
439
440
441 bool InsetText::showInsetDialog(BufferView *) const
442 {
443         return false;
444 }
445
446
447 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
448 {
449         clear();
450         Paragraph & first = paragraphs().front();
451         for (unsigned int i = 0; i < data.length(); ++i)
452                 first.insertChar(i, data[i], font, trackChanges);
453 }
454
455
456 void InsetText::setAutoBreakRows(bool flag)
457 {
458         if (flag == text_.autoBreakRows_)
459                 return;
460
461         text_.autoBreakRows_ = flag;
462         if (flag)
463                 return;
464
465         // remove previously existing newlines
466         ParagraphList::iterator it = paragraphs().begin();
467         ParagraphList::iterator end = paragraphs().end();
468         for (; it != end; ++it)
469                 for (int i = 0; i < it->size(); ++i)
470                         if (it->isNewline(i))
471                                 // do not track the change, because the user
472                                 // is not allowed to revert/reject it
473                                 it->eraseChar(i, false);
474 }
475
476
477 void InsetText::setDrawFrame(bool flag)
478 {
479         drawFrame_ = flag;
480 }
481
482
483 ColorCode InsetText::frameColor() const
484 {
485         return frame_color_;
486 }
487
488
489 void InsetText::setFrameColor(ColorCode col)
490 {
491         frame_color_ = col;
492 }
493
494
495 void InsetText::appendParagraphs(ParagraphList & plist)
496 {
497         // There is little we can do here to keep track of changes.
498         // As of 2006/10/20, appendParagraphs is used exclusively by
499         // LyXTabular::setMultiColumn. In this context, the paragraph break
500         // is lost irreversibly and the appended text doesn't really change
501
502         ParagraphList & pl = paragraphs();
503
504         ParagraphList::iterator pit = plist.begin();
505         ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
506         ++pit;
507         mergeParagraph(buffer().params(), pl,
508                        distance(pl.begin(), ins) - 1);
509
510         for_each(pit, plist.end(),
511                  bind(&ParagraphList::push_back, ref(pl), _1));
512 }
513
514
515 void InsetText::addPreview(PreviewLoader & loader) const
516 {
517         ParagraphList::const_iterator pit = paragraphs().begin();
518         ParagraphList::const_iterator pend = paragraphs().end();
519
520         for (; pit != pend; ++pit) {
521                 InsetList::const_iterator it  = pit->insetList().begin();
522                 InsetList::const_iterator end = pit->insetList().end();
523                 for (; it != end; ++it)
524                         it->inset->addPreview(loader);
525         }
526 }
527
528
529 ParagraphList const & InsetText::paragraphs() const
530 {
531         return text_.paragraphs();
532 }
533
534
535 ParagraphList & InsetText::paragraphs()
536 {
537         return text_.paragraphs();
538 }
539
540
541 void InsetText::updateLabels(ParIterator const & it)
542 {
543         ParIterator it2 = it;
544         it2.forwardPos();
545         LASSERT(&it2.inset() == this && it2.pit() == 0, return);
546         if (producesOutput())
547                 buffer().updateLabels(it2);
548         else {
549                 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
550                 Counters const savecnt = tclass.counters();
551                 buffer().updateLabels(it2);
552                 tclass.counters() = savecnt;
553         }
554 }
555
556
557 void InsetText::addToToc(DocIterator const & cdit)
558 {
559         DocIterator dit = cdit;
560         dit.push_back(CursorSlice(*this));
561         Toc & toc = buffer().tocBackend().toc("tableofcontents");
562
563         BufferParams const & bufparams = buffer_->params();
564         const int min_toclevel = bufparams.documentClass().min_toclevel();
565
566         // For each paragraph, traverse its insets and let them add
567         // their toc items
568         ParagraphList & pars = paragraphs();
569         pit_type pend = paragraphs().size();
570         for (pit_type pit = 0; pit != pend; ++pit) {
571                 Paragraph const & par = pars[pit];
572                 dit.pit() = pit;
573                 // the string that goes to the toc (could be the optarg)
574                 docstring tocstring;
575                 InsetList::const_iterator it  = par.insetList().begin();
576                 InsetList::const_iterator end = par.insetList().end();
577                 for (; it != end; ++it) {
578                         Inset & inset = *it->inset;
579                         dit.pos() = it->pos;
580                         //lyxerr << (void*)&inset << " code: " << inset.lyxCode() << std::endl;
581                         inset.addToToc(dit);
582                         switch (inset.lyxCode()) {
583                         case OPTARG_CODE: {
584                                 if (!tocstring.empty())
585                                         break;
586                                 dit.pos() = 0;
587                                 Paragraph const & insetpar =
588                                         *static_cast<InsetOptArg&>(inset).paragraphs().begin();
589                                 if (!par.labelString().empty())
590                                         tocstring = par.labelString() + ' ';
591                                 tocstring += insetpar.asString(AS_STR_INSETS);
592                                 break;
593                         }
594                         default:
595                                 break;
596                         }
597                 }
598                 // now the toc entry for the paragraph
599                 int const toclevel = par.layout().toclevel;
600                 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
601                         dit.pos() = 0;
602                         // insert this into the table of contents
603                         if (tocstring.empty())
604                                 tocstring = par.asString(AS_STR_LABEL | AS_STR_INSETS);
605                         toc.push_back(TocItem(dit, toclevel - min_toclevel, tocstring));
606                 }
607                 
608                 // And now the list of changes.
609                 par.addChangesToToc(dit, buffer());
610         }
611 }
612
613
614 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
615 {
616         if (buffer().isClean())
617                 return Inset::notifyCursorLeaves(old, cur);
618         
619         // find text inset in old cursor
620         Cursor insetCur = old;
621         int scriptSlice = insetCur.find(this);
622         LASSERT(scriptSlice != -1, /**/);
623         insetCur.cutOff(scriptSlice);
624         LASSERT(&insetCur.inset() == this, /**/);
625         
626         // update the old paragraph's words
627         insetCur.paragraph().updateWords();
628         
629         return Inset::notifyCursorLeaves(old, cur);
630 }
631
632
633 bool InsetText::completionSupported(Cursor const & cur) const
634 {
635         //LASSERT(&cur.bv().cursor().inset() != this, return false);
636         return text_.completionSupported(cur);
637 }
638
639
640 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
641 {
642         return completionSupported(cur);
643 }
644
645
646 bool InsetText::automaticInlineCompletion() const
647 {
648         return lyxrc.completion_inline_text;
649 }
650
651
652 bool InsetText::automaticPopupCompletion() const
653 {
654         return lyxrc.completion_popup_text;
655 }
656
657
658 bool InsetText::showCompletionCursor() const
659 {
660         return lyxrc.completion_cursor_text;
661 }
662
663
664 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
665 {
666         return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
667 }
668
669
670 docstring InsetText::completionPrefix(Cursor const & cur) const
671 {
672         if (!completionSupported(cur))
673                 return docstring();
674         return text_.completionPrefix(cur);
675 }
676
677
678 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
679         bool finished)
680 {
681         if (!completionSupported(cur))
682                 return false;
683
684         return text_.insertCompletion(cur, s, finished);
685 }
686
687
688 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y, 
689         Dimension & dim) const
690 {
691         TextMetrics const & tm = cur.bv().textMetrics(&text_);
692         tm.completionPosAndDim(cur, x, y, dim);
693 }
694
695
696 docstring InsetText::contextMenu(BufferView const &, int, int) const
697 {
698         return from_ascii("context-edit");
699 }
700
701
702 InsetCaption const * InsetText::getCaptionInset() const
703 {
704         ParagraphList::const_iterator pit = paragraphs().begin();
705         for (; pit != paragraphs().end(); ++pit) {
706                 InsetList::const_iterator it = pit->insetList().begin();
707                 for (; it != pit->insetList().end(); ++it) {
708                         Inset & inset = *it->inset;
709                         if (inset.lyxCode() == CAPTION_CODE) {
710                                 InsetCaption const * ins =
711                                         static_cast<InsetCaption const *>(it->inset);
712                                 return ins;
713                         }
714                 }
715         }
716         return 0;
717 }
718
719
720 docstring InsetText::getCaptionText(OutputParams const & runparams) const
721 {
722         InsetCaption const * ins = getCaptionInset();
723         if (ins == 0)
724                 return docstring();
725
726         odocstringstream ods;
727         ins->getCaptionAsPlaintext(ods, runparams);
728         return ods.str();
729 }
730
731
732 docstring InsetText::getCaptionHTML(OutputParams const & runparams) const
733 {
734         InsetCaption const * ins = getCaptionInset();
735         if (ins == 0)
736                 return docstring();
737
738         odocstringstream ods;
739         docstring def = ins->getCaptionAsHTML(ods, runparams);
740         if (!def.empty())
741                 ods << def << '\n';
742         return ods.str();
743 }
744
745
746 } // namespace lyx