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