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