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