]> git.lyx.org Git - lyx.git/blob - src/insets/InsetText.cpp
The two lines deleted here attempt to call virtual functions from a constructor....
[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 "InsetList.h"
30 #include "Intl.h"
31 #include "Lexer.h"
32 #include "lyxfind.h"
33 #include "LyXRC.h"
34 #include "MetricsInfo.h"
35 #include "output_docbook.h"
36 #include "output_latex.h"
37 #include "OutputParams.h"
38 #include "output_plaintext.h"
39 #include "paragraph_funcs.h"
40 #include "Paragraph.h"
41 #include "ParagraphParameters.h"
42 #include "ParIterator.h"
43 #include "Row.h"
44 #include "sgml.h"
45 #include "TexRow.h"
46 #include "TextClass.h"
47 #include "Text.h"
48 #include "TextMetrics.h"
49 #include "TocBackend.h"
50
51 #include "frontends/alert.h"
52 #include "frontends/Painter.h"
53
54 #include "support/debug.h"
55 #include "support/gettext.h"
56 #include "support/lstrings.h"
57
58 #include <boost/bind.hpp>
59 #include "support/lassert.h"
60
61 using namespace std;
62 using namespace lyx::support;
63
64 using boost::bind;
65 using boost::ref;
66
67 namespace lyx {
68
69 using graphics::PreviewLoader;
70
71
72 /////////////////////////////////////////////////////////////////////
73
74 InsetText::InsetText(Buffer const & buf, bool useplain)
75         : drawFrame_(false), frame_color_(Color_insetframe)
76 {
77         setBuffer(const_cast<Buffer &>(buf));
78         initParagraphs(useplain);
79 }
80
81
82 InsetText::InsetText(InsetText const & in)
83         : Inset(in), text_()
84 {
85         text_.autoBreakRows_ = in.text_.autoBreakRows_;
86         drawFrame_ = in.drawFrame_;
87         frame_color_ = in.frame_color_;
88         text_.paragraphs() = in.text_.paragraphs();
89         setParagraphOwner();
90 }
91
92
93 void InsetText::setBuffer(Buffer & buf)
94 {
95         ParagraphList::iterator end = paragraphs().end();
96         for (ParagraphList::iterator it = paragraphs().begin(); it != end; ++it)
97                 it->setBuffer(buf);
98         Inset::setBuffer(buf);
99 }
100
101
102 void InsetText::initParagraphs(bool useplain)
103 {
104         LASSERT(paragraphs().empty(), /**/);
105         paragraphs().push_back(Paragraph());
106         Paragraph & ourpar = paragraphs().back();
107         ourpar.setInsetOwner(this);
108         DocumentClass const & dc = buffer_.params().documentClass();
109         Layout const & lay = useplain ? dc.plainLayout() : dc.defaultLayout();
110         ourpar.setLayout(lay);
111 }
112
113
114 void InsetText::setParagraphOwner()
115 {
116         for_each(paragraphs().begin(), paragraphs().end(),
117                  bind(&Paragraph::setInsetOwner, _1, this));
118 }
119
120
121 void InsetText::clear()
122 {
123         ParagraphList & pars = paragraphs();
124         LASSERT(!pars.empty(), /**/);
125
126         // This is a gross hack...
127         Layout const & old_layout = pars.begin()->layout();
128
129         pars.clear();
130         pars.push_back(Paragraph());
131         pars.begin()->setInsetOwner(this);
132         pars.begin()->setLayout(old_layout);
133 }
134
135
136 Dimension const InsetText::dimension(BufferView const & bv) const
137 {
138         TextMetrics const & tm = bv.textMetrics(&text_);
139         Dimension dim = tm.dimension();
140         dim.wid += 2 * TEXT_TO_INSET_OFFSET;
141         dim.des += TEXT_TO_INSET_OFFSET;
142         dim.asc += TEXT_TO_INSET_OFFSET;
143         return dim;
144 }
145
146
147 void InsetText::write(ostream & os) const
148 {
149         os << "Text\n";
150         text_.write(buffer(), os);
151 }
152
153
154 void InsetText::read(Lexer & lex)
155 {
156         clear();
157
158         // delete the initial paragraph
159         Paragraph oldpar = *paragraphs().begin();
160         paragraphs().clear();
161         ErrorList errorList;
162         lex.setContext("InsetText::read");
163         bool res = text_.read(buffer(), lex, errorList, this);
164
165         if (!res)
166                 lex.printError("Missing \\end_inset at this point. ");
167
168         // sanity check
169         // ensure we have at least one paragraph.
170         if (paragraphs().empty())
171                 paragraphs().push_back(oldpar);
172 }
173
174
175 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
176 {
177         TextMetrics & tm = mi.base.bv->textMetrics(&text_);
178
179         //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
180
181         // Hand font through to contained lyxtext:
182         tm.font_.fontInfo() = mi.base.font;
183         mi.base.textwidth -= 2 * TEXT_TO_INSET_OFFSET;
184         if (hasFixedWidth())
185                 tm.metrics(mi, dim, mi.base.textwidth);
186         else
187                 tm.metrics(mi, dim);
188         mi.base.textwidth += 2 * TEXT_TO_INSET_OFFSET;
189         dim.asc += TEXT_TO_INSET_OFFSET;
190         dim.des += TEXT_TO_INSET_OFFSET;
191         dim.wid += 2 * TEXT_TO_INSET_OFFSET;
192 }
193
194
195 void InsetText::draw(PainterInfo & pi, int x, int y) const
196 {
197         TextMetrics & tm = pi.base.bv->textMetrics(&text_);
198
199         if (drawFrame_ || pi.full_repaint) {
200                 int const w = tm.width() + TEXT_TO_INSET_OFFSET;
201                 int const yframe = y - TEXT_TO_INSET_OFFSET - tm.ascent();
202                 int const h = tm.height() + 2 * TEXT_TO_INSET_OFFSET;
203                 int const xframe = x + TEXT_TO_INSET_OFFSET / 2;
204                 if (pi.full_repaint)
205                         pi.pain.fillRectangle(xframe, yframe, w, h,
206                                 pi.backgroundColor(this));
207
208                 if (drawFrame_)
209                         pi.pain.rectangle(xframe, yframe, w, h, frameColor());
210         }
211         ColorCode const old_color = pi.background_color;
212         pi.background_color = pi.backgroundColor(this, false);
213
214         tm.draw(pi, x + TEXT_TO_INSET_OFFSET, y);
215
216         pi.background_color = old_color;
217 }
218
219
220 docstring InsetText::editMessage() const
221 {
222         return _("Opened Text Inset");
223 }
224
225
226 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
227 {
228         pit_type const pit = front ? 0 : paragraphs().size() - 1;
229         pos_type pos = front ? 0 : paragraphs().back().size();
230
231         // if visual information is not to be ignored, move to extreme right/left
232         if (entry_from != ENTRY_DIRECTION_IGNORE) {
233                 Cursor temp_cur = cur;
234                 temp_cur.pit() = pit;
235                 temp_cur.pos() = pos;
236                 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
237                 pos = temp_cur.pos();
238         }
239
240         text_.setCursor(cur.top(), pit, pos);
241         cur.clearSelection();
242         cur.finishUndo();
243 }
244
245
246 Inset * InsetText::editXY(Cursor & cur, int x, int y)
247 {
248         return cur.bv().textMetrics(&text_).editXY(cur, x, y);
249 }
250
251
252 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
253 {
254         LYXERR(Debug::ACTION, "InsetText::doDispatch()"
255                 << " [ cmd.action = " << cmd.action << ']');
256         text_.dispatch(cur, cmd);
257 }
258
259
260 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
261         FuncStatus & status) const
262 {
263         switch (cmd.action) {
264         case LFUN_LAYOUT:
265                 status.setEnabled(!forcePlainLayout());
266                 return true;
267
268         case LFUN_LAYOUT_PARAGRAPH:
269         case LFUN_PARAGRAPH_PARAMS:
270         case LFUN_PARAGRAPH_PARAMS_APPLY:
271         case LFUN_PARAGRAPH_SPACING:
272         case LFUN_PARAGRAPH_UPDATE:
273                 status.setEnabled(allowParagraphCustomization());
274                 return true;
275         default:
276                 return text_.getStatus(cur, cmd, status);
277         }
278 }
279
280
281 void InsetText::setChange(Change const & change)
282 {
283         ParagraphList::iterator pit = paragraphs().begin();
284         ParagraphList::iterator end = paragraphs().end();
285         for (; pit != end; ++pit) {
286                 pit->setChange(change);
287         }
288 }
289
290
291 void InsetText::acceptChanges(BufferParams const & bparams)
292 {
293         text_.acceptChanges(bparams);
294 }
295
296
297 void InsetText::rejectChanges(BufferParams const & bparams)
298 {
299         text_.rejectChanges(bparams);
300 }
301
302
303 int InsetText::latex(odocstream & os, OutputParams const & runparams) const
304 {
305         TexRow texrow;
306         latexParagraphs(buffer(), text_, os, texrow, runparams);
307         return texrow.rows();
308 }
309
310
311 int InsetText::plaintext(odocstream & os, OutputParams const & runparams) const
312 {
313         ParagraphList::const_iterator beg = paragraphs().begin();
314         ParagraphList::const_iterator end = paragraphs().end();
315         ParagraphList::const_iterator it = beg;
316         bool ref_printed = false;
317         int len = 0;
318         for (; it != end; ++it) {
319                 if (it != beg) {
320                         os << '\n';
321                         if (runparams.linelen > 0)
322                                 os << '\n';
323                 }
324                 odocstringstream oss;
325                 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed);
326                 docstring const str = oss.str();
327                 os << str;
328                 // FIXME: len is not computed fully correctly; in principle,
329                 // we have to count the characters after the last '\n'
330                 len = str.size();
331         }
332
333         return len;
334 }
335
336
337 int InsetText::docbook(odocstream & os, OutputParams const & runparams) const
338 {
339         docbookParagraphs(paragraphs(), buffer(), os, runparams);
340         return 0;
341 }
342
343
344 void InsetText::validate(LaTeXFeatures & features) const
345 {
346         for_each(paragraphs().begin(), paragraphs().end(),
347                  bind(&Paragraph::validate, _1, ref(features)));
348 }
349
350
351 void InsetText::cursorPos(BufferView const & bv,
352                 CursorSlice const & sl, bool boundary, int & x, int & y) const
353 {
354         x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
355         y = bv.textMetrics(&text_).cursorY(sl, boundary);
356 }
357
358
359 bool InsetText::showInsetDialog(BufferView *) const
360 {
361         return false;
362 }
363
364
365 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
366 {
367         clear();
368         Paragraph & first = paragraphs().front();
369         for (unsigned int i = 0; i < data.length(); ++i)
370                 first.insertChar(i, data[i], font, trackChanges);
371 }
372
373
374 void InsetText::setAutoBreakRows(bool flag)
375 {
376         if (flag == text_.autoBreakRows_)
377                 return;
378
379         text_.autoBreakRows_ = flag;
380         if (flag)
381                 return;
382
383         // remove previously existing newlines
384         ParagraphList::iterator it = paragraphs().begin();
385         ParagraphList::iterator end = paragraphs().end();
386         for (; it != end; ++it)
387                 for (int i = 0; i < it->size(); ++i)
388                         if (it->isNewline(i))
389                                 // do not track the change, because the user
390                                 // is not allowed to revert/reject it
391                                 it->eraseChar(i, false);
392 }
393
394
395 void InsetText::setDrawFrame(bool flag)
396 {
397         drawFrame_ = flag;
398 }
399
400
401 ColorCode InsetText::frameColor() const
402 {
403         return frame_color_;
404 }
405
406
407 void InsetText::setFrameColor(ColorCode col)
408 {
409         frame_color_ = col;
410 }
411
412
413 void InsetText::appendParagraphs(ParagraphList & plist)
414 {
415         // There is little we can do here to keep track of changes.
416         // As of 2006/10/20, appendParagraphs is used exclusively by
417         // LyXTabular::setMultiColumn. In this context, the paragraph break
418         // is lost irreversibly and the appended text doesn't really change
419
420         ParagraphList & pl = paragraphs();
421
422         ParagraphList::iterator pit = plist.begin();
423         ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
424         ++pit;
425         mergeParagraph(buffer().params(), pl,
426                        distance(pl.begin(), ins) - 1);
427
428         for_each(pit, plist.end(),
429                  bind(&ParagraphList::push_back, ref(pl), _1));
430 }
431
432
433 void InsetText::addPreview(PreviewLoader & loader) const
434 {
435         ParagraphList::const_iterator pit = paragraphs().begin();
436         ParagraphList::const_iterator pend = paragraphs().end();
437
438         for (; pit != pend; ++pit) {
439                 InsetList::const_iterator it  = pit->insetList().begin();
440                 InsetList::const_iterator end = pit->insetList().end();
441                 for (; it != end; ++it)
442                         it->inset->addPreview(loader);
443         }
444 }
445
446
447 ParagraphList const & InsetText::paragraphs() const
448 {
449         return text_.paragraphs();
450 }
451
452
453 ParagraphList & InsetText::paragraphs()
454 {
455         return text_.paragraphs();
456 }
457
458
459 void InsetText::updateLabels(ParIterator const & it)
460 {
461         ParIterator it2 = it;
462         it2.forwardPos();
463         LASSERT(&it2.inset() == this && it2.pit() == 0, /**/);
464         if (producesOutput())
465                 lyx::updateLabels(buffer(), it2);
466         else {
467                 DocumentClass const & tclass = buffer().params().documentClass();
468                 Counters const savecnt = tclass.counters();
469                 lyx::updateLabels(buffer(), it2);
470                 tclass.counters() = savecnt;
471         }
472 }
473
474
475 void InsetText::addToToc(DocIterator const & cdit)
476 {
477         DocIterator dit = cdit;
478         dit.push_back(CursorSlice(*this));
479         Toc & toc = buffer().tocBackend().toc("tableofcontents");
480
481         BufferParams const & bufparams = buffer_->params();
482         const int min_toclevel = bufparams.documentClass().min_toclevel();
483
484         // For each paragraph, traverse its insets and let them add
485         // their toc items
486         ParagraphList & pars = paragraphs();
487         pit_type pend = paragraphs().size();
488         for (pit_type pit = 0; pit != pend; ++pit) {
489                 Paragraph const & par = pars[pit];
490                 dit.pit() = pit;
491                 // the string that goes to the toc (could be the optarg)
492                 docstring tocstring;
493                 InsetList::const_iterator it  = par.insetList().begin();
494                 InsetList::const_iterator end = par.insetList().end();
495                 for (; it != end; ++it) {
496                         Inset & inset = *it->inset;
497                         dit.pos() = it->pos;
498                         //lyxerr << (void*)&inset << " code: " << inset.lyxCode() << std::endl;
499                         inset.addToToc(dit);
500                         switch (inset.lyxCode()) {
501                         case OPTARG_CODE: {
502                                 if (!tocstring.empty())
503                                         break;
504                                 dit.pos() = 0;
505                                 Paragraph const & insetpar =
506                                         *static_cast<InsetOptArg&>(inset).paragraphs().begin();
507                                 if (!par.labelString().empty())
508                                         tocstring = par.labelString() + ' ';
509                                 tocstring += insetpar.asString();
510                                 break;
511                         }
512                         default:
513                                 break;
514                         }
515                 }
516                 /// now the toc entry for the paragraph
517                 int const toclevel = par.layout().toclevel;
518                 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
519                         dit.pos() = 0;
520                         // insert this into the table of contents
521                         if (tocstring.empty())
522                                 tocstring = par.asString(AS_STR_LABEL);
523                         toc.push_back(TocItem(dit, toclevel - min_toclevel, tocstring));
524                 }
525                 
526                 // And now the list of changes.
527                 par.addChangesToToc(dit, buffer());
528         }
529 }
530
531
532 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
533 {
534         if (cur.buffer().isClean())
535                 return Inset::notifyCursorLeaves(old, cur);
536         
537         // find text inset in old cursor
538         Cursor insetCur = old;
539         int scriptSlice = insetCur.find(this);
540         LASSERT(scriptSlice != -1, /**/);
541         insetCur.cutOff(scriptSlice);
542         LASSERT(&insetCur.inset() == this, /**/);
543         
544         // update the old paragraph's words
545         insetCur.paragraph().updateWords(insetCur.top());
546         
547         return Inset::notifyCursorLeaves(old, cur);
548 }
549
550
551 bool InsetText::completionSupported(Cursor const & cur) const
552 {
553         Cursor const & bvCur = cur.bv().cursor();
554         if (&bvCur.inset() != this)
555                 return false;
556         return text_.completionSupported(cur);
557 }
558
559
560 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
561 {
562         return completionSupported(cur);
563 }
564
565
566 bool InsetText::automaticInlineCompletion() const
567 {
568         return lyxrc.completion_inline_text;
569 }
570
571
572 bool InsetText::automaticPopupCompletion() const
573 {
574         return lyxrc.completion_popup_text;
575 }
576
577
578 bool InsetText::showCompletionCursor() const
579 {
580         return lyxrc.completion_cursor_text;
581 }
582
583
584 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
585 {
586         return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
587 }
588
589
590 docstring InsetText::completionPrefix(Cursor const & cur) const
591 {
592         if (!completionSupported(cur))
593                 return docstring();
594         return text_.completionPrefix(cur);
595 }
596
597
598 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
599         bool finished)
600 {
601         if (!completionSupported(cur))
602                 return false;
603
604         return text_.insertCompletion(cur, s, finished);
605 }
606
607
608 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y, 
609         Dimension & dim) const
610 {
611         TextMetrics const & tm = cur.bv().textMetrics(&text_);
612         tm.completionPosAndDim(cur, x, y, dim);
613 }
614
615
616 docstring InsetText::contextMenu(BufferView const &, int, int) const
617 {
618         return from_ascii("context-edit");
619 }
620
621
622 } // namespace lyx