]> git.lyx.org Git - features.git/blob - src/insets/InsetText.cpp
* compile fix
[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 buf_.registeredWords().size();
84                 return theWordList().size();
85         }
86         ///
87         virtual docstring const & data(size_t idx) const
88         {
89 //              return buf_.registeredWords().word(idx);
90                 return theWordList().word(idx);
91         }
92
93 private:
94         ///
95         Buffer const & buf_;
96         ///
97         size_t pos_;
98 };
99
100
101 /////////////////////////////////////////////////////////////////////
102
103 InsetText::InsetText(BufferParams const & bp)
104         : drawFrame_(false), frame_color_(Color_insetframe)
105 {
106         paragraphs().push_back(Paragraph());
107         Paragraph & ourpar = paragraphs().back();
108         ourpar.setEmptyOrDefaultLayout(bp.textClass());
109         ourpar.setInsetOwner(this);
110 }
111
112
113 InsetText::InsetText(InsetText const & in)
114         : Inset(in), text_()
115 {
116         text_.autoBreakRows_ = in.text_.autoBreakRows_;
117         drawFrame_ = in.drawFrame_;
118         frame_color_ = in.frame_color_;
119         text_.paragraphs() = in.text_.paragraphs();
120         setParagraphOwner();
121 }
122
123
124 InsetText::InsetText()
125 {}
126
127
128 void InsetText::setParagraphOwner()
129 {
130         for_each(paragraphs().begin(), paragraphs().end(),
131                  bind(&Paragraph::setInsetOwner, _1, this));
132 }
133
134
135 void InsetText::clear()
136 {
137         ParagraphList & pars = paragraphs();
138
139         // This is a gross hack...
140         LayoutPtr old_layout = pars.begin()->layout();
141
142         pars.clear();
143         pars.push_back(Paragraph());
144         pars.begin()->setInsetOwner(this);
145         pars.begin()->setLayout(old_layout);
146 }
147
148
149 Inset * InsetText::clone() const
150 {
151         return new InsetText(*this);
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(Buffer const & buf, ostream & os) const
167 {
168         os << "Text\n";
169         text_.write(buf, os);
170 }
171
172
173 void InsetText::read(Buffer const & buf, 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(buf, 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 const 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(Buffer const & buf, odocstream & os,
303                      OutputParams const & runparams) const
304 {
305         TexRow texrow;
306         latexParagraphs(buf, text_, os, texrow, runparams);
307         return texrow.rows();
308 }
309
310
311 int InsetText::plaintext(Buffer const & buf, odocstream & os,
312                          OutputParams const & runparams) const
313 {
314         ParagraphList::const_iterator beg = paragraphs().begin();
315         ParagraphList::const_iterator end = paragraphs().end();
316         ParagraphList::const_iterator it = beg;
317         bool ref_printed = false;
318         int len = 0;
319         for (; it != end; ++it) {
320                 if (it != beg) {
321                         os << '\n';
322                         if (runparams.linelen > 0)
323                                 os << '\n';
324                 }
325                 odocstringstream oss;
326                 writePlaintextParagraph(buf, *it, oss, runparams, ref_printed);
327                 docstring const str = oss.str();
328                 os << str;
329                 // FIXME: len is not computed fully correctly; in principle,
330                 // we have to count the characters after the last '\n'
331                 len = str.size();
332         }
333
334         return len;
335 }
336
337
338 int InsetText::docbook(Buffer const & buf, odocstream & os,
339                        OutputParams const & runparams) const
340 {
341         docbookParagraphs(paragraphs(), buf, os, runparams);
342         return 0;
343 }
344
345
346 void InsetText::validate(LaTeXFeatures & features) const
347 {
348         for_each(paragraphs().begin(), paragraphs().end(),
349                  bind(&Paragraph::validate, _1, ref(features)));
350 }
351
352
353 void InsetText::cursorPos(BufferView const & bv,
354                 CursorSlice const & sl, bool boundary, int & x, int & y) const
355 {
356         x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
357         y = bv.textMetrics(&text_).cursorY(sl, boundary);
358 }
359
360
361 bool InsetText::showInsetDialog(BufferView *) const
362 {
363         return false;
364 }
365
366
367 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
368 {
369         clear();
370         Paragraph & first = paragraphs().front();
371         for (unsigned int i = 0; i < data.length(); ++i)
372                 first.insertChar(i, data[i], font, trackChanges);
373 }
374
375
376 void InsetText::setAutoBreakRows(bool flag)
377 {
378         if (flag == text_.autoBreakRows_)
379                 return;
380
381         text_.autoBreakRows_ = flag;
382         if (flag)
383                 return;
384
385         // remove previously existing newlines
386         ParagraphList::iterator it = paragraphs().begin();
387         ParagraphList::iterator end = paragraphs().end();
388         for (; it != end; ++it)
389                 for (int i = 0; i < it->size(); ++i)
390                         if (it->isNewline(i))
391                                 // do not track the change, because the user
392                                 // is not allowed to revert/reject it
393                                 it->eraseChar(i, false);
394 }
395
396
397 void InsetText::setDrawFrame(bool flag)
398 {
399         drawFrame_ = flag;
400 }
401
402
403 ColorCode InsetText::frameColor() const
404 {
405         return frame_color_;
406 }
407
408
409 void InsetText::setFrameColor(ColorCode col)
410 {
411         frame_color_ = col;
412 }
413
414
415 void InsetText::appendParagraphs(Buffer * buffer, ParagraphList & plist)
416 {
417         // There is little we can do here to keep track of changes.
418         // As of 2006/10/20, appendParagraphs is used exclusively by
419         // LyXTabular::setMultiColumn. In this context, the paragraph break
420         // is lost irreversibly and the appended text doesn't really change
421
422         ParagraphList & pl = paragraphs();
423
424         ParagraphList::iterator pit = plist.begin();
425         ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
426         ++pit;
427         mergeParagraph(buffer->params(), pl,
428                        distance(pl.begin(), ins) - 1);
429
430         for_each(pit, plist.end(),
431                  bind(&ParagraphList::push_back, ref(pl), _1));
432 }
433
434
435 void InsetText::addPreview(PreviewLoader & loader) const
436 {
437         ParagraphList::const_iterator pit = paragraphs().begin();
438         ParagraphList::const_iterator pend = paragraphs().end();
439
440         for (; pit != pend; ++pit) {
441                 InsetList::const_iterator it  = pit->insetList().begin();
442                 InsetList::const_iterator end = pit->insetList().end();
443                 for (; it != end; ++it)
444                         it->inset->addPreview(loader);
445         }
446 }
447
448
449 //FIXME: instead of this hack, which only works by chance,
450 // cells should have their own insetcell type, which returns CELL_CODE!
451 bool InsetText::neverIndent(Buffer const & buffer) const
452 {
453         // this is only true for tabular cells
454         return !text_.isMainText(buffer) && lyxCode() == TEXT_CODE;
455 }
456
457
458 ParagraphList const & InsetText::paragraphs() const
459 {
460         return text_.paragraphs();
461 }
462
463
464 ParagraphList & InsetText::paragraphs()
465 {
466         return text_.paragraphs();
467 }
468
469
470 void InsetText::updateLabels(Buffer const & buf, ParIterator const & it)
471 {
472         ParIterator it2 = it;
473         it2.forwardPos();
474         BOOST_ASSERT(&it2.inset() == this && it2.pit() == 0);
475         lyx::updateLabels(buf, it2);
476 }
477
478
479 bool InsetText::completionSupported(Cursor const & cur) const
480 {
481         Cursor const & bvCur = cur.bv().cursor();
482         if (&bvCur.inset() != this)
483                 return false;
484         Paragraph const & par = cur.paragraph();
485         return cur.pos() > 0
486                 && (cur.pos() >= par.size() || !par.isLetter(cur.pos()))
487                 && par.isLetter(cur.pos() - 1);
488 }
489
490
491 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
492 {
493         return completionSupported(cur);
494 }
495
496
497 bool InsetText::automaticInlineCompletion() const
498 {
499         return lyxrc.completion_inline_text;
500 }
501
502
503 bool InsetText::automaticPopupCompletion() const
504 {
505         return lyxrc.completion_popup_text;
506 }
507
508
509 Inset::CompletionList const * InsetText::createCompletionList(
510         Cursor const & cur) const
511 {
512         if (!completionSupported(cur))
513                 return 0;
514
515         return new TextCompletionList(cur);
516 }
517
518
519 docstring InsetText::previousWord(Buffer const & buffer,
520         CursorSlice const & sl) const
521 {
522         CursorSlice from = sl;
523         CursorSlice to = sl;
524         text_.getWord(from, to, PREVIOUS_WORD);
525         if (sl == from || to == from)
526                 return docstring();
527         
528         Paragraph const & par = sl.paragraph();
529         return par.asString(buffer, from.pos(), to.pos(), false);
530 }
531
532
533 docstring InsetText::completionPrefix(Cursor const & cur) const
534 {
535         if (!completionSupported(cur))
536                 return docstring();
537         
538         return previousWord(cur.buffer(), cur.top());
539 }
540
541
542 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
543         bool /*finished*/)
544 {
545         if (!completionSupported(cur))
546                 return false;
547
548         BOOST_ASSERT(cur.bv().cursor() == cur);
549         cur.insert(s);
550         cur.bv().cursor() = cur;
551         return true;
552 }
553
554
555 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y, 
556         Dimension & dim) const
557 {
558         Cursor const & bvcur = cur.bv().cursor();
559         
560         // get word in front of cursor
561         docstring word = previousWord(cur.buffer(), bvcur.top());
562         DocIterator wordStart = bvcur;
563         wordStart.pos() -= word.length();
564         
565         // get position on screen of the word start and end
566         Point lxy = cur.bv().getPos(wordStart, false);
567         Point rxy = cur.bv().getPos(bvcur, bvcur.boundary());
568         
569         // calculate dimensions of the word
570         TextMetrics const & tm = cur.bv().textMetrics(&text_);
571         dim = tm.rowHeight(bvcur.pit(), wordStart.pos(), bvcur.pos(), false);
572         dim.wid = abs(rxy.x_ - lxy.x_);
573         
574         // calculate position of word
575         y = lxy.y_;
576         x = min(rxy.x_, lxy.x_);
577         
578         //lyxerr << "wid=" << dim.width() << " x=" << x << " y=" << y << " lxy.x_=" << lxy.x_ << " rxy.x_=" << rxy.x_ << " word=" << word << std::endl;
579         //lyxerr << " wordstart=" << wordStart << " bvcur=" << bvcur << " cur=" << cur << std::endl;
580 }
581
582
583 } // namespace lyx