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