]> git.lyx.org Git - lyx.git/blob - src/buffer_funcs.C
* output_plaintext.C: cosmetics in comment: line length cannot be < 0
[lyx.git] / src / buffer_funcs.C
1 /**
2  * \file buffer_funcs.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Alfredo Braunstein
8  *
9  * Full author contact details are available in file CREDITS.
10  *
11  */
12
13 #include <config.h>
14
15 #include "buffer_funcs.h"
16 #include "buffer.h"
17 #include "bufferlist.h"
18 #include "bufferparams.h"
19 #include "dociterator.h"
20 #include "counters.h"
21 #include "errorlist.h"
22 #include "Floating.h"
23 #include "FloatList.h"
24 #include "gettext.h"
25 #include "language.h"
26 #include "LaTeX.h"
27 #include "lyxtextclass.h"
28 #include "paragraph.h"
29 #include "paragraph_funcs.h"
30 #include "ParagraphList.h"
31 #include "ParagraphParameters.h"
32 #include "pariterator.h"
33 #include "lyxvc.h"
34 #include "texrow.h"
35 #include "TocBackend.h"
36 #include "vc-backend.h"
37
38 #include "frontends/Alert.h"
39
40 #include "insets/insetbibitem.h"
41 #include "insets/insetinclude.h"
42
43 #include "support/filetools.h"
44 #include "support/fs_extras.h"
45 #include "support/lyxlib.h"
46
47 #include <boost/bind.hpp>
48 #include <boost/filesystem/operations.hpp>
49
50
51 namespace lyx {
52
53 using namespace std;
54
55 using support::bformat;
56 using support::FileName;
57 using support::libFileSearch;
58 using support::makeAbsPath;
59 using support::makeDisplayPath;
60 using support::onlyFilename;
61 using support::onlyPath;
62 using support::unlink;
63
64 using std::min;
65 using std::string;
66
67 namespace Alert = frontend::Alert;
68 namespace fs = boost::filesystem;
69
70 namespace {
71
72 bool readFile(Buffer * const b, FileName const & s)
73 {
74         BOOST_ASSERT(b);
75
76         // File information about normal file
77         if (!fs::exists(s.toFilesystemEncoding())) {
78                 docstring const file = makeDisplayPath(s.absFilename(), 50);
79                 docstring text = bformat(_("The specified document\n%1$s"
80                                                      "\ncould not be read."), file);
81                 Alert::error(_("Could not read document"), text);
82                 return false;
83         }
84
85         // Check if emergency save file exists and is newer.
86         FileName const e(s.absFilename() + ".emergency");
87
88         if (fs::exists(e.toFilesystemEncoding()) &&
89             fs::exists(s.toFilesystemEncoding()) &&
90             fs::last_write_time(e.toFilesystemEncoding()) > fs::last_write_time(s.toFilesystemEncoding()))
91         {
92                 docstring const file = makeDisplayPath(s.absFilename(), 20);
93                 docstring const text =
94                         bformat(_("An emergency save of the document "
95                                   "%1$s exists.\n\n"
96                                                "Recover emergency save?"), file);
97                 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
98                                       _("&Recover"),  _("&Load Original"),
99                                       _("&Cancel")))
100                 {
101                 case 0:
102                         // the file is not saved if we load the emergency file.
103                         b->markDirty();
104                         return b->readFile(e);
105                 case 1:
106                         break;
107                 default:
108                         return false;
109                 }
110         }
111
112         // Now check if autosave file is newer.
113         FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
114
115         if (fs::exists(a.toFilesystemEncoding()) &&
116             fs::exists(s.toFilesystemEncoding()) &&
117             fs::last_write_time(a.toFilesystemEncoding()) > fs::last_write_time(s.toFilesystemEncoding()))
118         {
119                 docstring const file = makeDisplayPath(s.absFilename(), 20);
120                 docstring const text =
121                         bformat(_("The backup of the document "
122                                   "%1$s is newer.\n\nLoad the "
123                                                "backup instead?"), file);
124                 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
125                                       _("&Load backup"), _("Load &original"),
126                                       _("&Cancel") ))
127                 {
128                 case 0:
129                         // the file is not saved if we load the autosave file.
130                         b->markDirty();
131                         return b->readFile(a);
132                 case 1:
133                         // Here we delete the autosave
134                         unlink(a);
135                         break;
136                 default:
137                         return false;
138                 }
139         }
140         return b->readFile(s);
141 }
142
143
144 } // namespace anon
145
146
147
148 bool loadLyXFile(Buffer * b, FileName const & s)
149 {
150         BOOST_ASSERT(b);
151
152         if (fs::is_readable(s.toFilesystemEncoding())) {
153                 if (readFile(b, s)) {
154                         b->lyxvc().file_found_hook(s);
155                         if (!fs::is_writable(s.toFilesystemEncoding()))
156                                 b->setReadonly(true);
157                         return true;
158                 }
159         } else {
160                 docstring const file = makeDisplayPath(s.absFilename(), 20);
161                 // Here we probably should run
162                 if (LyXVC::file_not_found_hook(s)) {
163                         docstring const text =
164                                 bformat(_("Do you want to retrieve the document"
165                                                        " %1$s from version control?"), file);
166                         int const ret = Alert::prompt(_("Retrieve from version control?"),
167                                 text, 0, 1, _("&Retrieve"), _("&Cancel"));
168
169                         if (ret == 0) {
170                                 // How can we know _how_ to do the checkout?
171                                 // With the current VC support it has to be,
172                                 // a RCS file since CVS do not have special ,v files.
173                                 RCS::retrieve(s);
174                                 return loadLyXFile(b, s);
175                         }
176                 }
177         }
178         return false;
179 }
180
181 // FIXME newFile() should probably be a member method of Application...
182 Buffer * newFile(string const & filename, string const & templatename,
183                  bool const isNamed)
184 {
185         // get a free buffer
186         Buffer * b = theBufferList().newBuffer(filename);
187         BOOST_ASSERT(b);
188
189         FileName tname;
190         // use defaults.lyx as a default template if it exists.
191         if (templatename.empty())
192                 tname = libFileSearch("templates", "defaults.lyx");
193         else
194                 tname = makeAbsPath(templatename);
195
196         if (!tname.empty()) {
197                 if (!b->readFile(tname)) {
198                         docstring const file = makeDisplayPath(tname.absFilename(), 50);
199                         docstring const text  = bformat(
200                                 _("The specified document template\n%1$s\ncould not be read."),
201                                 file);
202                         Alert::error(_("Could not read template"), text);
203                         theBufferList().release(b);
204                         return 0;
205                 }
206         }
207
208         if (!isNamed) {
209                 b->setUnnamed();
210                 b->setFileName(filename);
211         }
212
213         b->setReadonly(false);
214         b->fully_loaded(true);
215         b->updateDocLang(b->params().language);
216
217         return b;
218 }
219
220
221 void bufferErrors(Buffer const & buf, TeXErrors const & terr,
222                                   ErrorList & errorList)
223 {
224         TeXErrors::Errors::const_iterator cit = terr.begin();
225         TeXErrors::Errors::const_iterator end = terr.end();
226
227         for (; cit != end; ++cit) {
228                 int id_start = -1;
229                 int pos_start = -1;
230                 int errorrow = cit->error_in_line;
231                 bool found = buf.texrow().getIdFromRow(errorrow, id_start,
232                                                        pos_start);
233                 int id_end = -1;
234                 int pos_end = -1;
235                 do {
236                         ++errorrow;
237                         found = buf.texrow().getIdFromRow(errorrow, id_end,
238                                                           pos_end);
239                 } while (found && id_start == id_end && pos_start == pos_end);
240
241                 errorList.push_back(ErrorItem(cit->error_desc,
242                         cit->error_text, id_start, pos_start, pos_end));
243         }
244 }
245
246
247 string const bufferFormat(Buffer const & buffer)
248 {
249         if (buffer.isDocBook())
250                 return "docbook";
251         else if (buffer.isLiterate())
252                 return "literate";
253         else
254                 return "latex";
255 }
256
257
258 int countWords(DocIterator const & from, DocIterator const & to)
259 {
260         int count = 0;
261         bool inword = false;
262         for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
263                 // Copied and adapted from isLetter() in ControlSpellChecker
264                 if (dit.inTexted()
265                     && dit.pos() != dit.lastpos()
266                     && dit.paragraph().isLetter(dit.pos())
267                     && !dit.paragraph().isDeleted(dit.pos())) {
268                         if (!inword) {
269                                 ++count;
270                                 inword = true;
271                         }
272                 } else if (inword)
273                         inword = false;
274         }
275
276         return count;
277 }
278
279
280 namespace {
281
282 depth_type getDepth(DocIterator const & it)
283 {
284         depth_type depth = 0;
285         for (size_t i = 0 ; i < it.depth() ; ++i)
286                 if (!it[i].inset().inMathed())
287                         depth += it[i].paragraph().getDepth() + 1;
288         // remove 1 since the outer inset does not count
289         return depth - 1;
290 }
291
292 depth_type getItemDepth(ParIterator const & it)
293 {
294         Paragraph const & par = *it;
295         LYX_LABEL_TYPES const labeltype = par.layout()->labeltype;
296
297         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
298                 return 0;
299
300         // this will hold the lowest depth encountered up to now.
301         depth_type min_depth = getDepth(it);
302         ParIterator prev_it = it;
303         while (true) {
304                 if (prev_it.pit())
305                         --prev_it.top().pit();
306                 else {
307                         // start of nested inset: go to outer par
308                         prev_it.pop_back();
309                         if (prev_it.empty()) {
310                                 // start of document: nothing to do
311                                 return 0;
312                         }
313                 }
314
315                 // We search for the first paragraph with same label
316                 // that is not more deeply nested.
317                 Paragraph & prev_par = *prev_it;
318                 depth_type const prev_depth = getDepth(prev_it);
319                 if (labeltype == prev_par.layout()->labeltype) {
320                         if (prev_depth < min_depth) {
321                                 return prev_par.itemdepth + 1;
322                         }
323                         else if (prev_depth == min_depth) {
324                                 return prev_par.itemdepth;
325                         }
326                 }
327                 min_depth = std::min(min_depth, prev_depth);
328                 // small optimization: if we are at depth 0, we won't
329                 // find anything else
330                 if (prev_depth == 0) {
331                         return 0;
332                 }
333         }
334 }
335
336
337 bool needEnumCounterReset(ParIterator const & it)
338 {
339         Paragraph const & par = *it;
340         BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
341         depth_type const cur_depth = par.getDepth();
342         ParIterator prev_it = it;
343         while (prev_it.pit()) {
344                 --prev_it.top().pit();
345                 Paragraph const & prev_par = *prev_it;
346                 if (prev_par.getDepth() <= cur_depth)
347                         return  prev_par.layout()->labeltype != LABEL_ENUMERATE;
348         }
349         // start of nested inset: reset
350         return true;
351 }
352
353
354 // set the label of a paragraph. This includes the counters.
355 void setLabel(Buffer const & buf, ParIterator & it, LyXTextClass const & textclass)
356 {
357         Paragraph & par = *it;
358         LyXLayout_ptr const & layout = par.layout();
359         Counters & counters = textclass.counters();
360
361         if (it.pit() == 0) {
362                 par.params().appendix(par.params().startOfAppendix());
363         } else {
364                 par.params().appendix(it.plist()[it.pit() - 1].params().appendix());
365                 if (!par.params().appendix() &&
366                     par.params().startOfAppendix()) {
367                         par.params().appendix(true);
368                         textclass.counters().reset();
369                 }
370         }
371
372         // Compute the item depth of the paragraph
373         par.itemdepth = getItemDepth(it);
374
375         if (layout->margintype == MARGIN_MANUAL) {
376                 if (par.params().labelWidthString().empty())
377                         par.params().labelWidthString(par.translateIfPossible(layout->labelstring(), buf.params()));
378         } else {
379                 par.params().labelWidthString(docstring());
380         }
381
382         // Optimisation: setLabel() can be called for each for each
383         // paragraph of the document. So we make the string static to
384         // avoid the repeated instanciation.
385         static docstring itemlabel;
386
387         // is it a layout that has an automatic label?
388         if (layout->labeltype == LABEL_COUNTER) {
389                 if (layout->toclevel <= buf.params().secnumdepth
390                     && (layout->latextype != LATEX_ENVIRONMENT
391                         || isFirstInSequence(it.pit(), it.plist()))) {
392                         counters.step(layout->counter);
393                         par.params().labelString(
394                                 par.expandLabel(layout, buf.params()));
395                 } else
396                         par.params().labelString(docstring());
397
398         } else if (layout->labeltype == LABEL_ITEMIZE) {
399                 // At some point of time we should do something more
400                 // clever here, like:
401                 //   par.params().labelString(
402                 //    buf.params().user_defined_bullet(par.itemdepth).getText());
403                 // for now, use a simple hardcoded label
404                 switch (par.itemdepth) {
405                 case 0:
406                         itemlabel = char_type(0x2022);
407                         break;
408                 case 1:
409                         itemlabel = char_type(0x2013);
410                         break;
411                 case 2:
412                         itemlabel = char_type(0x2217);
413                         break;
414                 case 3:
415                         itemlabel = char_type(0x2219); // or 0x00b7
416                         break;
417                 }
418                 par.params().labelString(itemlabel);
419
420         } else if (layout->labeltype == LABEL_ENUMERATE) {
421                 // FIXME
422                 // Yes I know this is a really, really! bad solution
423                 // (Lgb)
424                 docstring enumcounter = from_ascii("enum");
425
426                 switch (par.itemdepth) {
427                 case 2:
428                         enumcounter += 'i';
429                 case 1:
430                         enumcounter += 'i';
431                 case 0:
432                         enumcounter += 'i';
433                         break;
434                 case 3:
435                         enumcounter += "iv";
436                         break;
437                 default:
438                         // not a valid enumdepth...
439                         break;
440                 }
441
442                 // Maybe we have to reset the enumeration counter.
443                 if (needEnumCounterReset(it))
444                         counters.reset(enumcounter);
445
446                 counters.step(enumcounter);
447
448                 string format;
449
450                 switch (par.itemdepth) {
451                 case 0:
452                         format = N_("\\arabic{enumi}.");
453                         break;
454                 case 1:
455                         format = N_("(\\alph{enumii})");
456                         break;
457                 case 2:
458                         format = N_("\\roman{enumiii}.");
459                         break;
460                 case 3:
461                         format = N_("\\Alph{enumiv}.");
462                         break;
463                 default:
464                         // not a valid enumdepth...
465                         break;
466                 }
467
468                 par.params().labelString(counters.counterLabel(
469                         par.translateIfPossible(from_ascii(format), buf.params())));
470
471         } else if (layout->labeltype == LABEL_BIBLIO) {// ale970302
472                 counters.step(from_ascii("bibitem"));
473                 int number = counters.value(from_ascii("bibitem"));
474                 if (par.bibitem())
475                         par.bibitem()->setCounter(number);
476
477                 par.params().labelString(
478                         par.translateIfPossible(layout->labelstring(), buf.params()));
479                 // In biblio shouldn't be following counters but...
480         } else if (layout->labeltype == LABEL_SENSITIVE) {
481                 // Search for the first float or wrap inset in the iterator
482                 size_t i = it.depth();
483                 InsetBase * in;
484                 while (i > 0) {
485                         --i;
486                         in = &it[i].inset();
487                         if (in->lyxCode() == InsetBase::FLOAT_CODE
488                             || in->lyxCode() == InsetBase::WRAP_CODE)
489                                 break;
490                 }
491                 docstring const & type = in->getInsetName();
492
493                 if (!type.empty()) {
494                         Floating const & fl = textclass.floats().getType(to_ascii(type));
495                         // FIXME UNICODE
496                         counters.step(from_ascii(fl.type()));
497
498                         // Doesn't work... yet.
499                         par.params().labelString(par.translateIfPossible(
500                                 bformat(from_ascii("%1$s #:"), from_utf8(fl.name())),
501                                 buf.params()));
502                 } else {
503                         // par->SetLayout(0);
504                         par.params().labelString(par.translateIfPossible(
505                                 layout->labelstring(), buf.params()));
506                 }
507
508         } else if (layout->labeltype == LABEL_NO_LABEL)
509                 par.params().labelString(docstring());
510         else
511                 par.params().labelString(
512                         par.translateIfPossible(layout->labelstring(), buf.params()));
513 }
514
515 } // anon namespace
516
517
518 bool updateCurrentLabel(Buffer const & buf,
519         ParIterator & it)
520 {
521     if (it == par_iterator_end(buf.inset()))
522         return false;
523
524 //      if (it.lastpit == 0 && LyXText::isMainText(buf))
525 //              return false;
526
527         switch (it->layout()->labeltype) {
528
529         case LABEL_NO_LABEL:
530         case LABEL_MANUAL:
531         case LABEL_BIBLIO:
532         case LABEL_TOP_ENVIRONMENT:
533         case LABEL_CENTERED_TOP_ENVIRONMENT:
534         case LABEL_STATIC:
535         case LABEL_ITEMIZE:
536                 setLabel(buf, it, buf.params().getLyXTextClass());
537                 return true;
538
539         case LABEL_SENSITIVE:
540         case LABEL_COUNTER:
541         // do more things with enumerate later
542         case LABEL_ENUMERATE:
543                 return false;
544         }
545
546         // This is dead code which get rid of a warning:
547         return true;
548 }
549
550
551 void updateLabels(Buffer const & buf,
552         ParIterator & from, ParIterator & to, bool childonly)
553 {
554         for (ParIterator it = from; it != to; ++it) {
555                 if (it.pit() > it.lastpit())
556                         return;
557                 if (!updateCurrentLabel (buf, it)) {
558                         updateLabels(buf, childonly);
559                         return;
560                 }
561         }
562 }
563
564
565 void updateLabels(Buffer const & buf, ParIterator & iter, bool childonly)
566 {
567         if (updateCurrentLabel(buf, iter))
568                 return;
569
570         updateLabels(buf, childonly);
571 }
572
573
574 void updateLabels(Buffer const & buf, bool childonly)
575 {
576         // Use the master text class also for child documents
577         LyXTextClass const & textclass = buf.params().getLyXTextClass();
578
579         if (!childonly) {
580                 // If this is a child document start with the master
581                 Buffer const * const master = buf.getMasterBuffer();
582                 if (master != &buf) {
583                         updateLabels(*master);
584                         return;
585                 }
586
587                 // start over the counters
588                 textclass.counters().reset();
589         }
590
591         ParIterator const end = par_iterator_end(buf.inset());
592
593         for (ParIterator it = par_iterator_begin(buf.inset()); it != end; ++it) {
594                 // reduce depth if necessary
595                 if (it.pit()) {
596                         Paragraph const & prevpar = it.plist()[it.pit() - 1];
597                         it->params().depth(min(it->params().depth(),
598                                                prevpar.getMaxDepthAfter()));
599                 } else
600                         it->params().depth(0);
601
602                 // set the counter for this paragraph
603                 setLabel(buf, it, textclass);
604
605                 // Now included docs
606                 InsetList::const_iterator iit = it->insetlist.begin();
607                 InsetList::const_iterator end = it->insetlist.end();
608                 for (; iit != end; ++iit) {
609                         if (iit->inset->lyxCode() == InsetBase::INCLUDE_CODE)
610                                 static_cast<InsetInclude const *>(iit->inset)
611                                         ->updateLabels(buf);
612                 }
613         }
614
615         const_cast<Buffer &>(buf).tocBackend().update();
616 }
617
618
619 } // namespace lyx