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