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