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