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