]> git.lyx.org Git - lyx.git/blob - src/buffer.C
53c5b39230c8157898026e93bb677985fe9c5da7
[lyx.git] / src / buffer.C
1 /**
2  * \file buffer.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  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "buffer.h"
14
15 #include "author.h"
16 #include "buffer_funcs.h"
17 #include "bufferlist.h"
18 #include "bufferparams.h"
19 #include "counters.h"
20 #include "Bullet.h"
21 #include "Chktex.h"
22 #include "debug.h"
23 #include "errorlist.h"
24 #include "exporter.h"
25 #include "format.h"
26 #include "funcrequest.h"
27 #include "gettext.h"
28 #include "iterators.h"
29 #include "language.h"
30 #include "LaTeX.h"
31 #include "LaTeXFeatures.h"
32 #include "LyXAction.h"
33 #include "lyxlex.h"
34 #include "lyxtext.h"
35 #include "lyxrc.h"
36 #include "lyxvc.h"
37 #include "messages.h"
38 #include "output.h"
39 #include "output_docbook.h"
40 #include "output_latex.h"
41 #include "output_linuxdoc.h"
42 #include "paragraph.h"
43 #include "paragraph_funcs.h"
44 #include "ParagraphParameters.h"
45 #include "PosIterator.h"
46 #include "sgml.h"
47 #include "texrow.h"
48 #include "undo.h"
49 #include "version.h"
50
51 #include "insets/insetbibitem.h"
52 #include "insets/insetbibtex.h"
53 #include "insets/insetinclude.h"
54 #include "insets/insettext.h"
55
56 #include "frontends/Alert.h"
57
58 #include "graphics/Previews.h"
59
60 #include "support/FileInfo.h"
61 #include "support/filetools.h"
62 #include "support/gzstream.h"
63 #include "support/lyxlib.h"
64 #include "support/os.h"
65 #include "support/path.h"
66 #include "support/textutils.h"
67 #include "support/tostr.h"
68
69 #include <boost/bind.hpp>
70
71 #include "support/std_sstream.h"
72
73 #include <iomanip>
74 #include <stack>
75
76 #include <utime.h>
77
78 #ifdef HAVE_LOCALE
79 #endif
80
81 using lyx::pos_type;
82
83 using lyx::support::AddName;
84 using lyx::support::atoi;
85 using lyx::support::bformat;
86 using lyx::support::ChangeExtension;
87 using lyx::support::cmd_ret;
88 using lyx::support::CreateBufferTmpDir;
89 using lyx::support::destroyDir;
90 using lyx::support::FileInfo;
91 using lyx::support::FileInfo;
92 using lyx::support::getExtFromContents;
93 using lyx::support::IsDirWriteable;
94 using lyx::support::IsFileWriteable;
95 using lyx::support::LibFileSearch;
96 using lyx::support::ltrim;
97 using lyx::support::MakeAbsPath;
98 using lyx::support::MakeDisplayPath;
99 using lyx::support::MakeLatexName;
100 using lyx::support::OnlyFilename;
101 using lyx::support::OnlyPath;
102 using lyx::support::Path;
103 using lyx::support::QuoteName;
104 using lyx::support::removeAutosaveFile;
105 using lyx::support::rename;
106 using lyx::support::RunCommand;
107 using lyx::support::split;
108 using lyx::support::strToInt;
109 using lyx::support::subst;
110 using lyx::support::tempName;
111 using lyx::support::trim;
112
113 namespace os = lyx::support::os;
114
115 using std::endl;
116 using std::for_each;
117 using std::make_pair;
118
119 using std::ifstream;
120 using std::ios;
121 using std::ostream;
122 using std::ostringstream;
123 using std::ofstream;
124 using std::pair;
125 using std::stack;
126 using std::vector;
127 using std::string;
128
129
130 // all these externs should eventually be removed.
131 extern BufferList bufferlist;
132
133 namespace {
134
135 const int LYX_FORMAT = 227;
136
137 } // namespace anon
138
139
140 typedef std::map<string, bool> DepClean;
141
142 struct Buffer::Impl
143 {
144         Impl(Buffer & parent, string const & file, bool readonly);
145
146         limited_stack<Undo> undostack;
147         limited_stack<Undo> redostack;
148         BufferParams params;
149         LyXVC lyxvc;
150         string temppath;
151         bool nicefile;
152         TexRow texrow;
153
154         /// need to regenerate .tex ?
155         DepClean dep_clean;
156
157         /// is save needed
158         mutable bool lyx_clean;
159
160         /// is autosave needed
161         mutable bool bak_clean;
162
163         /// is this a unnamed file (New...)
164         bool unnamed;
165
166         /// buffer is r/o
167         bool read_only;
168
169         /// name of the file the buffer is associated with.
170         string filename;
171
172         /// The path to the document file.
173         string filepath;
174
175         boost::scoped_ptr<Messages> messages;
176
177         /** set to true only when the file is fully loaded.
178          *  Used to prevent the premature generation of previews
179          *  and by the citation inset.
180          */
181         bool file_fully_loaded;
182
183         /// our Text
184         LyXText text;
185 };
186
187
188 Buffer::Impl::Impl(Buffer & parent, string const & file, bool readonly_)
189         : nicefile(true),
190           lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
191           filename(file), filepath(OnlyPath(file)), file_fully_loaded(false),
192                 text(0, 0)
193 {
194         lyxvc.buffer(&parent);
195         if (readonly_ || lyxrc.use_tempdir)
196                 temppath = CreateBufferTmpDir();
197 }
198
199
200 Buffer::Buffer(string const & file, bool ronly)
201         : pimpl_(new Impl(*this, file, ronly))
202 {
203         lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
204 }
205
206
207 Buffer::~Buffer()
208 {
209         lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
210         // here the buffer should take care that it is
211         // saved properly, before it goes into the void.
212
213         closing();
214
215         if (!temppath().empty() && destroyDir(temppath()) != 0) {
216                 Alert::warning(_("Could not remove temporary directory"),
217                         bformat(_("Could not remove the temporary directory %1$s"), temppath()));
218         }
219
220         // Remove any previewed LaTeX snippets associated with this buffer.
221         lyx::graphics::Previews::get().removeLoader(*this);
222 }
223
224
225 LyXText & Buffer::text() const
226 {
227         return const_cast<LyXText &>(pimpl_->text);
228 }
229
230
231 limited_stack<Undo> & Buffer::undostack()
232 {
233         return pimpl_->undostack;
234 }
235
236
237 limited_stack<Undo> const & Buffer::undostack() const
238 {
239         return pimpl_->undostack;
240 }
241
242
243 limited_stack<Undo> & Buffer::redostack()
244 {
245         return pimpl_->redostack;
246 }
247
248
249 limited_stack<Undo> const & Buffer::redostack() const
250 {
251         return pimpl_->redostack;
252 }
253
254
255 BufferParams & Buffer::params()
256 {
257         return pimpl_->params;
258 }
259
260
261 BufferParams const & Buffer::params() const
262 {
263         return pimpl_->params;
264 }
265
266
267 ParagraphList & Buffer::paragraphs()
268 {
269         return pimpl_->text.paragraphs();
270 }
271
272
273 ParagraphList const & Buffer::paragraphs() const
274 {
275         return pimpl_->text.paragraphs();
276 }
277
278
279 LyXVC & Buffer::lyxvc()
280 {
281         return pimpl_->lyxvc;
282 }
283
284
285 LyXVC const & Buffer::lyxvc() const
286 {
287         return pimpl_->lyxvc;
288 }
289
290
291 string const & Buffer::temppath() const
292 {
293         return pimpl_->temppath;
294 }
295
296
297 bool & Buffer::niceFile()
298 {
299         return pimpl_->nicefile;
300 }
301
302
303 bool Buffer::niceFile() const
304 {
305         return pimpl_->nicefile;
306 }
307
308
309 TexRow & Buffer::texrow()
310 {
311         return pimpl_->texrow;
312 }
313
314
315 TexRow const & Buffer::texrow() const
316 {
317         return pimpl_->texrow;
318 }
319
320
321 string const Buffer::getLatexName(bool no_path) const
322 {
323         string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
324         return no_path ? OnlyFilename(name) : name;
325 }
326
327
328 pair<Buffer::LogType, string> const Buffer::getLogName() const
329 {
330         string const filename = getLatexName(false);
331
332         if (filename.empty())
333                 return make_pair(Buffer::latexlog, string());
334
335         string path = OnlyPath(filename);
336
337         if (lyxrc.use_tempdir || !IsDirWriteable(path))
338                 path = temppath();
339
340         string const fname = AddName(path,
341                                      OnlyFilename(ChangeExtension(filename,
342                                                                   ".log")));
343         string const bname =
344                 AddName(path, OnlyFilename(
345                         ChangeExtension(filename,
346                                         formats.extension("literate") + ".out")));
347
348         // If no Latex log or Build log is newer, show Build log
349
350         FileInfo const f_fi(fname);
351         FileInfo const b_fi(bname);
352
353         if (b_fi.exist() &&
354             (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
355                 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
356                 return make_pair(Buffer::buildlog, bname);
357         }
358         lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
359         return make_pair(Buffer::latexlog, fname);
360 }
361
362
363 void Buffer::setReadonly(bool flag)
364 {
365         if (pimpl_->read_only != flag) {
366                 pimpl_->read_only = flag;
367                 readonly(flag);
368         }
369 }
370
371
372 void Buffer::setFileName(string const & newfile)
373 {
374         pimpl_->filename = MakeAbsPath(newfile);
375         pimpl_->filepath = OnlyPath(pimpl_->filename);
376         setReadonly(IsFileWriteable(pimpl_->filename) == 0);
377         updateTitles();
378 }
379
380
381 // We'll remove this later. (Lgb)
382 namespace {
383
384 void unknownClass(string const & unknown)
385 {
386         Alert::warning(_("Unknown document class"),
387                 bformat(_("Using the default document class, because the "
388                         "class %1$s is unknown."), unknown));
389 }
390
391 } // anon
392
393
394 int Buffer::readHeader(LyXLex & lex)
395 {
396         int unknown_tokens = 0;
397
398         while (lex.isOK()) {
399                 lex.nextToken();
400                 string const token = lex.getString();
401
402                 if (token.empty())
403                         continue;
404
405                 if (token == "\\end_header")
406                         break;
407
408                 lyxerr[Debug::PARSER] << "Handling header token: `"
409                                       << token << '\'' << endl;
410
411
412                 string unknown = params().readToken(lex, token);
413                 if (!unknown.empty()) {
414                         if (unknown[0] != '\\') {
415                                 unknownClass(unknown);
416                         } else {
417                                 ++unknown_tokens;
418                                 string const s = bformat(_("Unknown token: "
419                                                            "%1$s %2$s\n"),
420                                                          token,
421                                                          lex.getString());
422                                 error(ErrorItem(_("Header error"), s,
423                                                 -1, 0, 0));
424                         }
425                 }
426         }
427         return unknown_tokens;
428 }
429
430
431 // candidate for move to BufferView
432 // (at least some parts in the beginning of the func)
433 //
434 // Uwe C. Schroeder
435 // changed to be public and have one parameter
436 // if par = 0 normal behavior
437 // else insert behavior
438 // Returns false if "\end_document" is not read (Asger)
439 bool Buffer::readBody(LyXLex & lex)
440 {
441         bool the_end_read = false;
442
443         if (paragraphs().empty()) {
444                 readHeader(lex);
445                 if (!params().getLyXTextClass().load()) {
446                         string theclass = params().getLyXTextClass().name();
447                         Alert::error(_("Can't load document class"), bformat(
448                                         "Using the default document class, because the "
449                                         " class %1$s could not be loaded.", theclass));
450                         params().textclass = 0;
451                 }
452         } else {
453                 // We don't want to adopt the parameters from the
454                 // document we insert, so read them into a temporary buffer
455                 // and then discard it
456
457                 Buffer tmpbuf("", false);
458                 tmpbuf.readHeader(lex);
459         }
460
461         if (text().read(*this, lex))
462                 the_end_read = true;
463
464         return the_end_read;
465 }
466
467
468 // needed to insert the selection
469 void Buffer::insertStringAsLines(ParagraphList::iterator & par, pos_type & pos,
470                                  LyXFont const & fn, string const & str)
471 {
472         LyXLayout_ptr const & layout = par->layout();
473
474         LyXFont font = fn;
475
476         par->checkInsertChar(font);
477         // insert the string, don't insert doublespace
478         bool space_inserted = true;
479         bool autobreakrows = !par->inInset() ||
480                 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
481         for(string::const_iterator cit = str.begin();
482             cit != str.end(); ++cit) {
483                 if (*cit == '\n') {
484                         if (autobreakrows && (!par->empty() || par->allowEmpty())) {
485                                 breakParagraph(params(), paragraphs(), par, pos,
486                                                layout->isEnvironment());
487                                 ++par;
488                                 pos = 0;
489                                 space_inserted = true;
490                         } else {
491                                 continue;
492                         }
493                         // do not insert consecutive spaces if !free_spacing
494                 } else if ((*cit == ' ' || *cit == '\t') &&
495                            space_inserted && !par->isFreeSpacing()) {
496                         continue;
497                 } else if (*cit == '\t') {
498                         if (!par->isFreeSpacing()) {
499                                 // tabs are like spaces here
500                                 par->insertChar(pos, ' ', font);
501                                 ++pos;
502                                 space_inserted = true;
503                         } else {
504                                 const pos_type nb = 8 - pos % 8;
505                                 for (pos_type a = 0; a < nb ; ++a) {
506                                         par->insertChar(pos, ' ', font);
507                                         ++pos;
508                                 }
509                                 space_inserted = true;
510                         }
511                 } else if (!IsPrintable(*cit)) {
512                         // Ignore unprintables
513                         continue;
514                 } else {
515                         // just insert the character
516                         par->insertChar(pos, *cit, font);
517                         ++pos;
518                         space_inserted = (*cit == ' ');
519                 }
520
521         }
522 }
523
524
525 bool Buffer::readFile(string const & filename)
526 {
527         // Check if the file is compressed.
528         string const format = getExtFromContents(filename);
529         if (format == "gzip" || format == "zip" || format == "compress") {
530                 params().compressed = true;
531         }
532
533         bool ret = readFile(filename, paragraphs().begin());
534
535         // After we have read a file, we must ensure that the buffer
536         // language is set and used in the gui.
537         // If you know of a better place to put this, please tell me. (Lgb)
538         updateDocLang(params().language);
539
540         return ret;
541 }
542
543
544 bool Buffer::readFile(string const & filename, ParagraphList::iterator pit)
545 {
546         LyXLex lex(0, 0);
547         lex.setFile(filename);
548
549         return readFile(lex, filename, pit);
550 }
551
552
553 bool Buffer::fully_loaded() const
554 {
555         return pimpl_->file_fully_loaded;
556 }
557
558
559 void Buffer::fully_loaded(bool value)
560 {
561         pimpl_->file_fully_loaded = value;
562 }
563
564
565 bool Buffer::readFile(LyXLex & lex, string const & filename,
566                       ParagraphList::iterator pit)
567 {
568         BOOST_ASSERT(!filename.empty());
569
570         if (!lex.isOK()) {
571                 Alert::error(_("Document could not be read"),
572                              bformat(_("%1$s could not be read."), filename));
573                 return false;
574         }
575
576         lex.next();
577         string const token(lex.getString());
578
579         if (!lex.isOK()) {
580                 Alert::error(_("Document could not be read"),
581                              bformat(_("%1$s could not be read."), filename));
582                 return false;
583         }
584
585         // the first token _must_ be...
586         if (token != "\\lyxformat") {
587                 lyxerr << "Token: " << token << endl;
588
589                 Alert::error(_("Document format failure"),
590                              bformat(_("%1$s is not a LyX document."),
591                                        filename));
592                 return false;
593         }
594
595         lex.eatLine();
596         string tmp_format = lex.getString();
597         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
598         // if present remove ".," from string.
599         string::size_type dot = tmp_format.find_first_of(".,");
600         //lyxerr << "           dot found at " << dot << endl;
601         if (dot != string::npos)
602                         tmp_format.erase(dot, 1);
603         int file_format = strToInt(tmp_format);
604         //lyxerr << "format: " << file_format << endl;
605
606         if (file_format > LYX_FORMAT) {
607                 Alert::warning(_("Document format failure"),
608                                bformat(_("%1$s was created with a newer"
609                                          " version of LyX. This is likely to"
610                                          " cause problems."),
611                                          filename));
612         } else if (file_format < LYX_FORMAT) {
613                 string const tmpfile = tempName();
614                 string command = LibFileSearch("lyx2lyx", "lyx2lyx");
615                 if (command.empty()) {
616                         Alert::error(_("Conversion script not found"),
617                                      bformat(_("%1$s is from an earlier"
618                                                " version of LyX, but the"
619                                                " conversion script lyx2lyx"
620                                                " could not be found."),
621                                                filename));
622                         return false;
623                 }
624                 command += " -t"
625                         + tostr(LYX_FORMAT)
626                         + " -o " + tmpfile + ' '
627                         + QuoteName(filename);
628                 lyxerr[Debug::INFO] << "Running '"
629                                     << command << '\''
630                                     << endl;
631                 cmd_ret const ret = RunCommand(command);
632                 if (ret.first != 0) {
633                         Alert::error(_("Conversion script failed"),
634                                      bformat(_("%1$s is from an earlier version"
635                                               " of LyX, but the lyx2lyx script"
636                                               " failed to convert it."),
637                                               filename));
638                         return false;
639                 } else {
640                         bool ret = readFile(tmpfile, pit);
641                         // Do stuff with tmpfile name and buffer name here.
642                         return ret;
643                 }
644
645         }
646
647         bool the_end = readBody(lex);
648         params().setPaperStuff();
649
650         if (!the_end) {
651                 Alert::error(_("Document format failure"),
652                              bformat(_("%1$s ended unexpectedly, which means"
653                                        " that it is probably corrupted."),
654                                        filename));
655         }
656         pimpl_->file_fully_loaded = true;
657         return true;
658 }
659
660
661 // Should probably be moved to somewhere else: BufferView? LyXView?
662 bool Buffer::save() const
663 {
664         // We don't need autosaves in the immediate future. (Asger)
665         resetAutosaveTimers();
666
667         // make a backup
668         string s;
669         if (lyxrc.make_backup) {
670                 s = fileName() + '~';
671                 if (!lyxrc.backupdir_path.empty())
672                         s = AddName(lyxrc.backupdir_path,
673                                     subst(os::slashify_path(s),'/','!'));
674
675                 // Rename is the wrong way of making a backup,
676                 // this is the correct way.
677                 /* truss cp fil fil2:
678                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
679                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
680                    open("LyXVC.lyx", O_RDONLY)                     = 3
681                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
682                    fstat(4, 0xEFFFF508)                            = 0
683                    fstat(3, 0xEFFFF508)                            = 0
684                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
685                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
686                    read(3, 0xEFFFD4A0, 8192)                       = 0
687                    close(4)                                        = 0
688                    close(3)                                        = 0
689                    chmod("LyXVC3.lyx", 0100644)                    = 0
690                    lseek(0, 0, SEEK_CUR)                           = 46440
691                    _exit(0)
692                 */
693
694                 // Should probably have some more error checking here.
695                 // Doing it this way, also makes the inodes stay the same.
696                 // This is still not a very good solution, in particular we
697                 // might loose the owner of the backup.
698                 FileInfo finfo(fileName());
699                 if (finfo.exist()) {
700                         mode_t fmode = finfo.getMode();
701                         struct utimbuf times = {
702                                 finfo.getAccessTime(),
703                                 finfo.getModificationTime() };
704
705                         ifstream ifs(fileName().c_str());
706                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
707                         if (ifs && ofs) {
708                                 ofs << ifs.rdbuf();
709                                 ifs.close();
710                                 ofs.close();
711                                 ::chmod(s.c_str(), fmode);
712
713                                 if (::utime(s.c_str(), &times)) {
714                                         lyxerr << "utime error." << endl;
715                                 }
716                         } else {
717                                 lyxerr << "LyX was not able to make "
718                                         "backup copy. Beware." << endl;
719                         }
720                 }
721         }
722
723         if (writeFile(fileName())) {
724                 markClean();
725                 removeAutosaveFile(fileName());
726         } else {
727                 // Saving failed, so backup is not backup
728                 if (lyxrc.make_backup) {
729                         rename(s, fileName());
730                 }
731                 return false;
732         }
733         return true;
734 }
735
736
737 bool Buffer::writeFile(string const & fname) const
738 {
739         if (pimpl_->read_only && (fname == fileName())) {
740                 return false;
741         }
742
743         FileInfo finfo(fname);
744         if (finfo.exist() && !finfo.writable()) {
745                 return false;
746         }
747
748         bool retval;
749
750         if (params().compressed) {
751                 gz::ogzstream ofs(fname.c_str());
752
753                 if (!ofs)
754                         return false;
755
756                 retval = do_writeFile(ofs);
757
758         } else {
759                 ofstream ofs(fname.c_str());
760                 if (!ofs)
761                         return false;
762
763                 retval = do_writeFile(ofs);
764         }
765
766         return retval;
767 }
768
769
770 bool Buffer::do_writeFile(ostream & ofs) const
771 {
772
773 #ifdef HAVE_LOCALE
774         // Use the standard "C" locale for file output.
775         ofs.imbue(std::locale::classic());
776 #endif
777
778         // The top of the file should not be written by params().
779
780         // write out a comment in the top of the file
781         ofs << "#LyX " << lyx_version
782             << " created this file. For more info see http://www.lyx.org/\n"
783             << "\\lyxformat " << LYX_FORMAT << "\n";
784
785         // now write out the buffer parameters.
786         params().writeFile(ofs);
787
788         ofs << "\\end_header\n";
789
790         // write the text
791         text().write(*this, ofs);
792
793         // Write marker that shows file is complete
794         ofs << "\n\\end_document" << endl;
795
796         // Shouldn't really be needed....
797         //ofs.close();
798
799         // how to check if close went ok?
800         // Following is an attempt... (BE 20001011)
801
802         // good() returns false if any error occured, including some
803         //        formatting error.
804         // bad()  returns true if something bad happened in the buffer,
805         //        which should include file system full errors.
806
807         bool status = true;
808         if (!ofs.good()) {
809                 status = false;
810 #if 0
811                 if (ofs.bad()) {
812                         lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
813                 } else {
814                         lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
815                                << endl;
816                 }
817 #endif
818         }
819
820         return status;
821 }
822
823
824 void Buffer::makeLaTeXFile(string const & fname,
825                            string const & original_path,
826                            OutputParams const & runparams,
827                            bool output_preamble, bool output_body)
828 {
829         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
830
831         ofstream ofs;
832         if (!openFileWrite(ofs, fname))
833                 return;
834
835         makeLaTeXFile(ofs, original_path,
836                       runparams, output_preamble, output_body);
837
838         ofs.close();
839         if (ofs.fail()) {
840                 lyxerr << "File was not closed properly." << endl;
841         }
842 }
843
844
845 void Buffer::makeLaTeXFile(ostream & os,
846                            string const & original_path,
847                            OutputParams const & runparams_in,
848                            bool output_preamble, bool output_body)
849 {
850         OutputParams runparams = runparams_in;
851         niceFile() = runparams.nice; // this will be used by Insetincludes.
852
853         // validate the buffer.
854         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
855         LaTeXFeatures features(*this, params());
856         validate(features);
857         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
858
859         texrow().reset();
860         // The starting paragraph of the coming rows is the
861         // first paragraph of the document. (Asger)
862         texrow().start(paragraphs().begin()->id(), 0);
863
864         if (output_preamble && runparams.nice) {
865                 os << "%% LyX " << lyx_version << " created this file.  "
866                         "For more info, see http://www.lyx.org/.\n"
867                         "%% Do not edit unless you really know what "
868                         "you are doing.\n";
869                 texrow().newline();
870                 texrow().newline();
871         }
872         lyxerr[Debug::INFO] << "lyx header finished" << endl;
873         // There are a few differences between nice LaTeX and usual files:
874         // usual is \batchmode and has a
875         // special input@path to allow the including of figures
876         // with either \input or \includegraphics (what figinsets do).
877         // input@path is set when the actual parameter
878         // original_path is set. This is done for usual tex-file, but not
879         // for nice-latex-file. (Matthias 250696)
880         if (output_preamble) {
881                 if (!runparams.nice) {
882                         // code for usual, NOT nice-latex-file
883                         os << "\\batchmode\n"; // changed
884                         // from \nonstopmode
885                         texrow().newline();
886                 }
887                 if (!original_path.empty()) {
888                         string inputpath = os::external_path(original_path);
889                         subst(inputpath, "~", "\\string~");
890                         os << "\\makeatletter\n"
891                             << "\\def\\input@path{{"
892                             << inputpath << "/}}\n"
893                             << "\\makeatother\n";
894                         texrow().newline();
895                         texrow().newline();
896                         texrow().newline();
897                 }
898
899                 // Write the preamble
900                 runparams.use_babel = params().writeLaTeX(os, features, texrow());
901
902                 if (!output_body)
903                         return;
904
905                 // make the body.
906                 os << "\\begin{document}\n";
907                 texrow().newline();
908         } // output_preamble
909         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
910
911         if (!lyxrc.language_auto_begin) {
912                 os << subst(lyxrc.language_command_begin, "$$lang",
913                              params().language->babel())
914                     << endl;
915                 texrow().newline();
916         }
917
918         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
919
920         // add this just in case after all the paragraphs
921         os << endl;
922         texrow().newline();
923
924         if (!lyxrc.language_auto_end) {
925                 os << subst(lyxrc.language_command_end, "$$lang",
926                              params().language->babel())
927                     << endl;
928                 texrow().newline();
929         }
930
931         if (output_preamble) {
932                 os << "\\end{document}\n";
933                 texrow().newline();
934
935                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
936         } else {
937                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
938                                      << endl;
939         }
940
941         // Just to be sure. (Asger)
942         texrow().newline();
943
944         lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
945         lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
946                             << '.' << endl;
947
948         // we want this to be true outside previews (for insetexternal)
949         niceFile() = true;
950 }
951
952
953 bool Buffer::isLatex() const
954 {
955         return params().getLyXTextClass().outputType() == LATEX;
956 }
957
958
959 bool Buffer::isLinuxDoc() const
960 {
961         return params().getLyXTextClass().outputType() == LINUXDOC;
962 }
963
964
965 bool Buffer::isLiterate() const
966 {
967         return params().getLyXTextClass().outputType() == LITERATE;
968 }
969
970
971 bool Buffer::isDocBook() const
972 {
973         return params().getLyXTextClass().outputType() == DOCBOOK;
974 }
975
976
977 bool Buffer::isSGML() const
978 {
979         LyXTextClass const & tclass = params().getLyXTextClass();
980
981         return tclass.outputType() == LINUXDOC ||
982                tclass.outputType() == DOCBOOK;
983 }
984
985
986 void Buffer::makeLinuxDocFile(string const & fname,
987                               OutputParams const & runparams,
988                               bool body_only )
989 {
990         ofstream ofs;
991         if (!openFileWrite(ofs, fname))
992                 return;
993
994         niceFile() = runparams.nice; // this will be used by included files.
995
996         LaTeXFeatures features(*this, params());
997
998         validate(features);
999
1000         texrow().reset();
1001
1002         LyXTextClass const & tclass = params().getLyXTextClass();
1003
1004         string top_element = tclass.latexname();
1005
1006         if (!body_only) {
1007                 ofs << tclass.class_header();
1008
1009                 string preamble = params().preamble;
1010                 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1011                          : fname;
1012                 preamble += features.getIncludedFiles(name);
1013                 preamble += features.getLyXSGMLEntities();
1014
1015                 if (!preamble.empty()) {
1016                         ofs << " [ " << preamble << " ]";
1017                 }
1018                 ofs << ">\n\n";
1019
1020                 if (params().options.empty())
1021                         sgml::openTag(ofs, 0, false, top_element);
1022                 else {
1023                         string top = top_element;
1024                         top += ' ';
1025                         top += params().options;
1026                         sgml::openTag(ofs, 0, false, top);
1027                 }
1028         }
1029
1030         ofs << "<!-- LyX "  << lyx_version
1031             << " created this file. For more info see http://www.lyx.org/"
1032             << " -->\n";
1033
1034         linuxdocParagraphs(*this, paragraphs(), ofs, runparams);
1035
1036         if (!body_only) {
1037                 ofs << "\n\n";
1038                 sgml::closeTag(ofs, 0, false, top_element);
1039         }
1040
1041         ofs.close();
1042         // How to check for successful close
1043
1044         // we want this to be true outside previews (for insetexternal)
1045         niceFile() = true;
1046 }
1047
1048
1049 void Buffer::makeDocBookFile(string const & fname,
1050                              OutputParams const & runparams,
1051                              bool only_body)
1052 {
1053         ofstream ofs;
1054         if (!openFileWrite(ofs, fname))
1055                 return;
1056
1057         niceFile() = runparams.nice; // this will be used by Insetincludes.
1058
1059         LaTeXFeatures features(*this, params());
1060         validate(features);
1061
1062         texrow().reset();
1063
1064         LyXTextClass const & tclass = params().getLyXTextClass();
1065         string top_element = tclass.latexname();
1066
1067         if (!only_body) {
1068                 ofs << subst(tclass.class_header(), "#", top_element);
1069
1070                 string preamble = params().preamble;
1071                 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1072                          : fname;
1073                 preamble += features.getIncludedFiles(name);
1074                 preamble += features.getLyXSGMLEntities();
1075
1076                 if (!preamble.empty()) {
1077                         ofs << "\n [ " << preamble << " ]";
1078                 }
1079                 ofs << ">\n\n";
1080         }
1081
1082         string top = top_element;
1083         top += " lang=\"";
1084         top += params().language->code();
1085         top += '"';
1086
1087         if (!params().options.empty()) {
1088                 top += ' ';
1089                 top += params().options;
1090         }
1091         sgml::openTag(ofs, 0, false, top);
1092
1093         ofs << "<!-- SGML/XML file was created by LyX " << lyx_version
1094             << "\n  See http://www.lyx.org/ for more information -->\n";
1095
1096         params().getLyXTextClass().counters().reset();
1097         docbookParagraphs(*this, paragraphs(), ofs, runparams);
1098
1099         ofs << "\n\n";
1100         sgml::closeTag(ofs, 0, false, top_element);
1101
1102         ofs.close();
1103         // How to check for successful close
1104
1105         // we want this to be true outside previews (for insetexternal)
1106         niceFile() = true;
1107 }
1108
1109
1110 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1111 // Other flags: -wall -v0 -x
1112 int Buffer::runChktex()
1113 {
1114         busy(true);
1115
1116         // get LaTeX-Filename
1117         string const name = getLatexName();
1118         string path = filePath();
1119
1120         string const org_path = path;
1121         if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
1122                 path = temppath();
1123         }
1124
1125         Path p(path); // path to LaTeX file
1126         message(_("Running chktex..."));
1127
1128         // Generate the LaTeX file if neccessary
1129         OutputParams runparams;
1130         runparams.flavor = OutputParams::LATEX;
1131         runparams.nice = false;
1132         makeLaTeXFile(name, org_path, runparams);
1133
1134         TeXErrors terr;
1135         Chktex chktex(lyxrc.chktex_command, name, filePath());
1136         int res = chktex.run(terr); // run chktex
1137
1138         if (res == -1) {
1139                 Alert::error(_("chktex failure"),
1140                              _("Could not run chktex successfully."));
1141         } else if (res > 0) {
1142                 // Insert all errors as errors boxes
1143                 bufferErrors(*this, terr);
1144         }
1145
1146         busy(false);
1147
1148         return res;
1149 }
1150
1151
1152 void Buffer::validate(LaTeXFeatures & features) const
1153 {
1154         LyXTextClass const & tclass = params().getLyXTextClass();
1155
1156         if (params().tracking_changes) {
1157                 features.require("dvipost");
1158                 features.require("color");
1159         }
1160
1161         // AMS Style is at document level
1162         if (params().use_amsmath == BufferParams::AMS_ON
1163             || tclass.provides(LyXTextClass::amsmath))
1164                 features.require("amsmath");
1165
1166         for_each(paragraphs().begin(), paragraphs().end(),
1167                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1168
1169         // the bullet shapes are buffer level not paragraph level
1170         // so they are tested here
1171         for (int i = 0; i < 4; ++i) {
1172                 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1173                         int const font = params().user_defined_bullet(i).getFont();
1174                         if (font == 0) {
1175                                 int const c = params()
1176                                         .user_defined_bullet(i)
1177                                         .getCharacter();
1178                                 if (c == 16
1179                                    || c == 17
1180                                    || c == 25
1181                                    || c == 26
1182                                    || c == 31) {
1183                                         features.require("latexsym");
1184                                 }
1185                         } else if (font == 1) {
1186                                 features.require("amssymb");
1187                         } else if ((font >= 2 && font <= 5)) {
1188                                 features.require("pifont");
1189                         }
1190                 }
1191         }
1192
1193         if (lyxerr.debugging(Debug::LATEX)) {
1194                 features.showStruct();
1195         }
1196 }
1197
1198
1199 void Buffer::getLabelList(std::vector<string> & list) const
1200 {
1201         /// if this is a child document and the parent is already loaded
1202         /// Use the parent's list instead  [ale990407]
1203         if (!params().parentname.empty()
1204             && bufferlist.exists(params().parentname)) {
1205                 Buffer const * tmp = bufferlist.getBuffer(params().parentname);
1206                 if (tmp) {
1207                         tmp->getLabelList(list);
1208                         return;
1209                 }
1210         }
1211
1212         for (inset_iterator it = inset_const_iterator_begin();
1213              it != inset_const_iterator_end(); ++it) {
1214                 it->getLabelList(*this, list);
1215         }
1216 }
1217
1218
1219 // This is also a buffer property (ale)
1220 void Buffer::fillWithBibKeys(std::vector<std::pair<string, string> > & keys)
1221         const
1222 {
1223         /// if this is a child document and the parent is already loaded
1224         /// use the parent's list instead  [ale990412]
1225         if (!params().parentname.empty() &&
1226             bufferlist.exists(params().parentname)) {
1227                 Buffer const * tmp = bufferlist.getBuffer(params().parentname);
1228                 if (tmp) {
1229                         tmp->fillWithBibKeys(keys);
1230                         return;
1231                 }
1232         }
1233
1234         for (inset_iterator it = inset_const_iterator_begin();
1235                 it != inset_const_iterator_end(); ++it) {
1236                 if (it->lyxCode() == InsetOld::BIBTEX_CODE) {
1237                         InsetBibtex const & inset =
1238                                 dynamic_cast<InsetBibtex const &>(*it);
1239                         inset.fillWithBibKeys(*this, keys);
1240                 } else if (it->lyxCode() == InsetOld::INCLUDE_CODE) {
1241                         InsetInclude const & inset =
1242                                 dynamic_cast<InsetInclude const &>(*it);
1243                         inset.fillWithBibKeys(*this, keys);
1244                 } else if (it->lyxCode() == InsetOld::BIBITEM_CODE) {
1245                         InsetBibitem const & inset =
1246                                 dynamic_cast<InsetBibitem const &>(*it);
1247                         string const key = inset.getContents();
1248                         string const opt = inset.getOptions();
1249                         string const ref; // = pit->asString(this, false);
1250                         string const info = opt + "TheBibliographyRef" + ref;
1251                         keys.push_back(pair<string, string>(key, info));
1252                 }
1253         }
1254 }
1255
1256
1257 bool Buffer::isDepClean(string const & name) const
1258 {
1259         DepClean::const_iterator it = pimpl_->dep_clean.find(name);
1260         if (it == pimpl_->dep_clean.end())
1261                 return true;
1262         return it->second;
1263 }
1264
1265
1266 void Buffer::markDepClean(string const & name)
1267 {
1268         pimpl_->dep_clean[name] = true;
1269 }
1270
1271
1272 bool Buffer::dispatch(string const & command, bool * result)
1273 {
1274         return dispatch(lyxaction.lookupFunc(command), result);
1275 }
1276
1277
1278 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1279 {
1280         bool dispatched = true;
1281
1282         switch (func.action) {
1283                 case LFUN_EXPORT: {
1284                         bool const tmp = Exporter::Export(this, func.argument, false);
1285                         if (result)
1286                                 *result = tmp;
1287                         break;
1288                 }
1289
1290                 default:
1291                         dispatched = false;
1292         }
1293         return dispatched;
1294 }
1295
1296
1297 void Buffer::changeLanguage(Language const * from, Language const * to)
1298 {
1299         lyxerr << "Changing Language!" << endl;
1300
1301         // Take care of l10n/i18n
1302         updateDocLang(to);
1303
1304         ParIterator end = par_iterator_end();
1305         for (ParIterator it = par_iterator_begin(); it != end; ++it)
1306                 it->changeLanguage(params(), from, to);
1307 }
1308
1309
1310 void Buffer::updateDocLang(Language const * nlang)
1311 {
1312         pimpl_->messages.reset(new Messages(nlang->code()));
1313 }
1314
1315
1316 bool Buffer::isMultiLingual()
1317 {
1318         ParIterator end = par_iterator_end();
1319         for (ParIterator it = par_iterator_begin(); it != end; ++it)
1320                 if (it->isMultiLingual(params()))
1321                         return true;
1322
1323         return false;
1324 }
1325
1326
1327 void Buffer::inset_iterator::setParagraph()
1328 {
1329         while (pit != pend) {
1330                 it = pit->insetlist.begin();
1331                 if (it != pit->insetlist.end())
1332                         return;
1333                 ++pit;
1334         }
1335 }
1336
1337
1338 ParIterator Buffer::getParFromID(int id) const
1339 {
1340 #warning FIXME: const correctness! (Andre)
1341         ParIterator it = const_cast<Buffer*>(this)->par_iterator_begin();
1342         ParIterator end = const_cast<Buffer*>(this)->par_iterator_end();
1343
1344 #warning FIXME, perhaps this func should return a ParIterator? (Lgb)
1345         if (id < 0) {
1346                 // John says this is called with id == -1 from undo
1347                 lyxerr << "getParFromID(), id: " << id << endl;
1348                 return end;
1349         }
1350
1351         for (; it != end; ++it)
1352                 if (it->id() == id)
1353                         return it;
1354
1355         return end;
1356 }
1357
1358
1359 bool Buffer::hasParWithID(int id) const
1360 {
1361         ParConstIterator it = par_iterator_begin();
1362         ParConstIterator end = par_iterator_end();
1363
1364         if (id < 0) {
1365                 // John says this is called with id == -1 from undo
1366                 lyxerr << "hasParWithID(), id: " << id << endl;
1367                 return 0;
1368         }
1369
1370         for (; it != end; ++it)
1371                 if (it->id() == id)
1372                         return true;
1373
1374         return false;
1375 }
1376
1377
1378 PosIterator Buffer::pos_iterator_begin()
1379 {
1380         return PosIterator(&paragraphs(), paragraphs().begin(), 0);
1381 }
1382
1383
1384 PosIterator Buffer::pos_iterator_end()
1385 {
1386         return PosIterator(&paragraphs(), paragraphs().end(), 0);
1387 }
1388
1389
1390 ParIterator Buffer::par_iterator_begin()
1391 {
1392         return ParIterator(paragraphs().begin(), paragraphs());
1393 }
1394
1395
1396 ParIterator Buffer::par_iterator_end()
1397 {
1398         return ParIterator(paragraphs().end(), paragraphs());
1399 }
1400
1401
1402 ParConstIterator Buffer::par_iterator_begin() const
1403 {
1404         ParagraphList const & pars = paragraphs();
1405         return ParConstIterator(const_cast<ParagraphList&>(pars).begin(), pars);
1406 }
1407
1408
1409 ParConstIterator Buffer::par_iterator_end() const
1410 {
1411         ParagraphList const & pars = paragraphs();
1412         return ParConstIterator(const_cast<ParagraphList&>(pars).end(), pars);
1413 }
1414
1415
1416 Language const * Buffer::getLanguage() const
1417 {
1418         return params().language;
1419 }
1420
1421
1422 string const Buffer::B_(string const & l10n) const
1423 {
1424         if (pimpl_->messages.get()) {
1425                 return pimpl_->messages->get(l10n);
1426         }
1427
1428         return _(l10n);
1429 }
1430
1431
1432 bool Buffer::isClean() const
1433 {
1434         return pimpl_->lyx_clean;
1435 }
1436
1437
1438 bool Buffer::isBakClean() const
1439 {
1440         return pimpl_->bak_clean;
1441 }
1442
1443
1444 void Buffer::markClean() const
1445 {
1446         if (!pimpl_->lyx_clean) {
1447                 pimpl_->lyx_clean = true;
1448                 updateTitles();
1449         }
1450         // if the .lyx file has been saved, we don't need an
1451         // autosave
1452         pimpl_->bak_clean = true;
1453 }
1454
1455
1456 void Buffer::markBakClean()
1457 {
1458         pimpl_->bak_clean = true;
1459 }
1460
1461
1462 void Buffer::setUnnamed(bool flag)
1463 {
1464         pimpl_->unnamed = flag;
1465 }
1466
1467
1468 bool Buffer::isUnnamed()
1469 {
1470         return pimpl_->unnamed;
1471 }
1472
1473
1474 void Buffer::markDirty()
1475 {
1476         if (pimpl_->lyx_clean) {
1477                 pimpl_->lyx_clean = false;
1478                 updateTitles();
1479         }
1480         pimpl_->bak_clean = false;
1481
1482         DepClean::iterator it = pimpl_->dep_clean.begin();
1483         DepClean::const_iterator const end = pimpl_->dep_clean.end();
1484
1485         for (; it != end; ++it) {
1486                 it->second = false;
1487         }
1488 }
1489
1490
1491 string const & Buffer::fileName() const
1492 {
1493         return pimpl_->filename;
1494 }
1495
1496
1497 string const & Buffer::filePath() const
1498 {
1499         return pimpl_->filepath;
1500 }
1501
1502
1503 bool Buffer::isReadonly() const
1504 {
1505         return pimpl_->read_only;
1506 }
1507
1508
1509 void Buffer::setParentName(string const & name)
1510 {
1511         params().parentname = name;
1512 }
1513
1514
1515 Buffer::inset_iterator::inset_iterator()
1516         : pit(), pend()
1517 {}
1518
1519
1520 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
1521         : pit(p), pend(e)
1522 {
1523         setParagraph();
1524 }
1525
1526
1527 Buffer::inset_iterator Buffer::inset_iterator_begin()
1528 {
1529         return inset_iterator(paragraphs().begin(), paragraphs().end());
1530 }
1531
1532
1533 Buffer::inset_iterator Buffer::inset_iterator_end()
1534 {
1535         return inset_iterator(paragraphs().end(), paragraphs().end());
1536 }
1537
1538
1539 Buffer::inset_iterator Buffer::inset_const_iterator_begin() const
1540 {
1541         ParagraphList & pars = const_cast<ParagraphList&>(paragraphs());
1542         return inset_iterator(pars.begin(), pars.end());
1543 }
1544
1545
1546 Buffer::inset_iterator Buffer::inset_const_iterator_end() const
1547 {
1548         ParagraphList & pars = const_cast<ParagraphList&>(paragraphs());
1549         return inset_iterator(pars.end(), pars.end());
1550 }
1551
1552
1553 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
1554 {
1555         if (pit != pend) {
1556                 ++it;
1557                 if (it == pit->insetlist.end()) {
1558                         ++pit;
1559                         setParagraph();
1560                 }
1561         }
1562         return *this;
1563 }
1564
1565
1566 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
1567 {
1568         inset_iterator tmp = *this;
1569         ++*this;
1570         return tmp;
1571 }
1572
1573
1574 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
1575 {
1576         return *it->inset;
1577 }
1578
1579
1580 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
1581 {
1582         return it->inset;
1583 }
1584
1585
1586 ParagraphList::iterator Buffer::inset_iterator::getPar() const
1587 {
1588         return pit;
1589 }
1590
1591
1592 lyx::pos_type Buffer::inset_iterator::getPos() const
1593 {
1594         return it->pos;
1595 }
1596
1597
1598 bool operator==(Buffer::inset_iterator const & iter1,
1599                 Buffer::inset_iterator const & iter2)
1600 {
1601         return iter1.pit == iter2.pit
1602                 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
1603 }
1604
1605
1606 bool operator!=(Buffer::inset_iterator const & iter1,
1607                 Buffer::inset_iterator const & iter2)
1608 {
1609         return !(iter1 == iter2);
1610 }