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