]> git.lyx.org Git - lyx.git/blob - src/insets/InsetText.cpp
9f54b337c0fafeeaeae4e44554340e6ed7b19cc2
[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
47 #include "frontends/alert.h"
48 #include "frontends/Painter.h"
49
50 #include "support/debug.h"
51 #include "support/gettext.h"
52 #include "support/lstrings.h"
53
54 #include <boost/bind.hpp>
55 #include <boost/assert.hpp>
56
57 using namespace std;
58 using namespace lyx::support;
59
60 using boost::bind;
61 using boost::ref;
62
63 namespace lyx {
64
65 using graphics::PreviewLoader;
66
67
68 class TextCompletionList : public Inset::CompletionList {
69 public:
70         ///
71         TextCompletionList(Cursor const & cur)
72         : buf_(cur.buffer()), it_(buf_.registeredWords().begin()), pos_(0) {}
73         ///
74         virtual ~TextCompletionList() {}
75
76         ///
77         virtual size_t size() const {
78                 return buf_.registeredWords().size();
79         }
80         ///
81         virtual docstring data(size_t idx) const {
82                 std::set<docstring>::iterator it
83                 = buf_.registeredWords().begin();
84                 for (size_t i = 0; i < idx; ++i)
85                         it++;
86                 return *it;
87         }
88
89 private:
90         Buffer const & buf_;
91         std::set<docstring>::iterator const it_;
92         size_t pos_;
93 };
94
95
96 /////////////////////////////////////////////////////////////////////
97
98 InsetText::InsetText(BufferParams const & bp)
99         : drawFrame_(false), frame_color_(Color_insetframe)
100 {
101         paragraphs().push_back(Paragraph());
102         Paragraph & ourpar = paragraphs().back();
103         if (useEmptyLayout())
104                 ourpar.layout(bp.getTextClass().emptyLayout());
105         else
106                 ourpar.layout(bp.getTextClass().defaultLayout());
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()->layout(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(Buffer const & buf, ostream & os) const
165 {
166         os << "Text\n";
167         text_.write(buf, os);
168 }
169
170
171 void InsetText::read(Buffer const & buf, 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(buf, 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 const 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(Buffer const & buf, odocstream & os,
301                      OutputParams const & runparams) const
302 {
303         TexRow texrow;
304         latexParagraphs(buf, text_, os, texrow, runparams);
305         return texrow.rows();
306 }
307
308
309 int InsetText::plaintext(Buffer const & buf, odocstream & os,
310                          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(buf, *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(Buffer const & buf, odocstream & os,
337                        OutputParams const & runparams) const
338 {
339         docbookParagraphs(paragraphs(), buf, os, runparams);
340         return 0;
341 }
342
343
344 void InsetText::validate(LaTeXFeatures & features) const
345 {
346         for_each(paragraphs().begin(), paragraphs().end(),
347                  bind(&Paragraph::validate, _1, ref(features)));
348 }
349
350
351 void InsetText::cursorPos(BufferView const & bv,
352                 CursorSlice const & sl, bool boundary, int & x, int & y) const
353 {
354         x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
355         y = bv.textMetrics(&text_).cursorY(sl, boundary);
356 }
357
358
359 bool InsetText::showInsetDialog(BufferView *) const
360 {
361         return false;
362 }
363
364
365 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
366 {
367         clear();
368         Paragraph & first = paragraphs().front();
369         for (unsigned int i = 0; i < data.length(); ++i)
370                 first.insertChar(i, data[i], font, trackChanges);
371 }
372
373
374 void InsetText::setAutoBreakRows(bool flag)
375 {
376         if (flag == text_.autoBreakRows_)
377                 return;
378
379         text_.autoBreakRows_ = flag;
380         if (flag)
381                 return;
382
383         // remove previously existing newlines
384         ParagraphList::iterator it = paragraphs().begin();
385         ParagraphList::iterator end = paragraphs().end();
386         for (; it != end; ++it)
387                 for (int i = 0; i < it->size(); ++i)
388                         if (it->isNewline(i))
389                                 // do not track the change, because the user
390                                 // is not allowed to revert/reject it
391                                 it->eraseChar(i, false);
392 }
393
394
395 void InsetText::setDrawFrame(bool flag)
396 {
397         drawFrame_ = flag;
398 }
399
400
401 ColorCode InsetText::frameColor() const
402 {
403         return frame_color_;
404 }
405
406
407 void InsetText::setFrameColor(ColorCode col)
408 {
409         frame_color_ = col;
410 }
411
412
413 void InsetText::appendParagraphs(Buffer * buffer, ParagraphList & plist)
414 {
415         // There is little we can do here to keep track of changes.
416         // As of 2006/10/20, appendParagraphs is used exclusively by
417         // LyXTabular::setMultiColumn. In this context, the paragraph break
418         // is lost irreversibly and the appended text doesn't really change
419
420         ParagraphList & pl = paragraphs();
421
422         ParagraphList::iterator pit = plist.begin();
423         ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
424         ++pit;
425         mergeParagraph(buffer->params(), pl,
426                        distance(pl.begin(), ins) - 1);
427
428         for_each(pit, plist.end(),
429                  bind(&ParagraphList::push_back, ref(pl), _1));
430 }
431
432
433 void InsetText::addPreview(PreviewLoader & loader) const
434 {
435         ParagraphList::const_iterator pit = paragraphs().begin();
436         ParagraphList::const_iterator pend = paragraphs().end();
437
438         for (; pit != pend; ++pit) {
439                 InsetList::const_iterator it  = pit->insetList().begin();
440                 InsetList::const_iterator end = pit->insetList().end();
441                 for (; it != end; ++it)
442                         it->inset->addPreview(loader);
443         }
444 }
445
446
447 //FIXME: instead of this hack, which only works by chance,
448 // cells should have their own insetcell type, which returns CELL_CODE!
449 bool InsetText::neverIndent(Buffer const & buffer) const
450 {
451         // this is only true for tabular cells
452         return !text_.isMainText(buffer) && lyxCode() == TEXT_CODE;
453 }
454
455
456 ParagraphList const & InsetText::paragraphs() const
457 {
458         return text_.paragraphs();
459 }
460
461
462 ParagraphList & InsetText::paragraphs()
463 {
464         return text_.paragraphs();
465 }
466
467
468 void InsetText::updateLabels(Buffer const & buf, ParIterator const & it)
469 {
470         ParIterator it2 = it;
471         it2.forwardPos();
472         BOOST_ASSERT(&it2.inset() == this && it2.pit() == 0);
473         lyx::updateLabels(buf, it2);
474 }
475
476
477 bool InsetText::completionSupported(Cursor const & cur) const
478 {
479         Cursor const & bvCur = cur.bv().cursor();
480         if (&bvCur.inset() != this)
481                 return false;
482         Paragraph const & par = cur.paragraph();
483         return cur.pos() > 0
484                 && !par.isLetter(cur.pos())
485                 && par.isLetter(cur.pos() - 1);
486 }
487
488
489 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
490 {
491         return completionSupported(cur);
492 }
493
494
495 bool InsetText::automaticInlineCompletion() const
496 {
497         return lyxrc.completion_inline_text;
498 }
499
500
501 bool InsetText::automaticPopupCompletion() const
502 {
503         return lyxrc.completion_popup_text;
504 }
505
506
507 Inset::CompletionListPtr InsetText::completionList(Cursor const & cur) const
508 {
509         if (!completionSupported(cur))
510                 return CompletionListPtr();
511
512         return CompletionListPtr(new TextCompletionList(cur));
513 }
514
515
516 docstring InsetText::previousWord(Buffer const & buffer, CursorSlice const & sl) const
517 {
518         CursorSlice from = sl;
519         CursorSlice to = sl;
520         text_.getWord(from, to, PREVIOUS_WORD);
521         if (sl == from || to == from)
522                 return docstring();
523         
524         Paragraph const & par = sl.paragraph();
525         return par.asString(buffer, from.pos(), to.pos(), false);
526 }
527
528
529 docstring InsetText::completionPrefix(Cursor const & cur) const
530 {
531         if (!completionSupported(cur))
532                 return docstring();
533         
534         return previousWord(cur.buffer(), cur.top());
535 }
536
537
538 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
539                                      bool finished)
540 {
541         if (!completionSupported(cur))
542                 return false;
543         
544         cur.insert(s);
545         return true;
546 }
547
548
549 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y, 
550                                         Dimension & dim) const
551 {
552         // get word in front of cursor
553         docstring word = previousWord(cur.buffer(), cur.top());
554         DocIterator wordStart = cur;
555         wordStart.pos() -= word.length();
556         
557         // get position on screen of the word start
558         Point lxy = cur.bv().getPos(wordStart, false);
559         x = lxy.x_;
560         y = lxy.y_;
561
562         // Calculate dimensions of the word
563         TextMetrics const & tm = cur.bv().textMetrics(&text_);
564         dim = tm.rowHeight(cur.pit(), wordStart.pos(), cur.pos(), false);
565         Point rxy = cur.bv().getPos(cur, cur.boundary());
566         dim.wid = abs(rxy.x_ - x);
567         x = (rxy.x_ < x) ? x - dim.wid : x; // for RTL
568 }
569
570
571 } // namespace lyx