]> git.lyx.org Git - lyx.git/blob - src/buffer.C
136065377866753173e44d1c47af27c7d3e4fee9
[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 = 236;
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         int line = -1;
397         int begin_header_line = -1;
398
399         while (lex.isOK()) {
400                 lex.next();
401                 string const token = lex.getString();
402
403                 if (token.empty())
404                         continue;
405
406                 if (token == "\\end_header")
407                         break;
408
409                 ++line;
410                 if (token == "\\begin_header") {
411                         begin_header_line = line;
412                         continue;
413                 }
414
415                 lyxerr[Debug::PARSER] << "Handling header token: `"
416                                       << token << '\'' << endl;
417
418                 string unknown = params().readToken(lex, token);
419                 if (!unknown.empty()) {
420                         if (unknown[0] != '\\' and token == "\\textclass") {
421                                 unknownClass(unknown);
422                         } else {
423                                 ++unknown_tokens;
424                                 string const s = bformat(_("Unknown token: "
425                                                            "%1$s %2$s\n"),
426                                                          token,
427                                                          lex.getString());
428                                 error(ErrorItem(_("Header error"), s,
429                                                 -1, 0, 0));
430                         }
431                 }
432         }
433         if (begin_header_line) {
434                 string const s = _("\\begin_header is missing");
435                 error(ErrorItem(_("Header error"), s, -1, 0, 0));
436         }
437         return unknown_tokens;
438 }
439
440
441 // Uwe C. Schroeder
442 // changed to be public and have one parameter
443 // Returns false if "\end_document" is not read (Asger)
444 bool Buffer::readDocument(LyXLex & lex)
445 {
446         lex.next();
447         string const token = lex.getString();
448         if (token != "\\begin_document") {
449                 string const s = _("\\begin_document is missing");
450                 error(ErrorItem(_("Header error"), s, -1, 0, 0));
451         }
452
453         if (paragraphs().empty()) {
454                 readHeader(lex);
455                 if (!params().getLyXTextClass().load()) {
456                         string theclass = params().getLyXTextClass().name();
457                         Alert::error(_("Can't load document class"), bformat(
458                                         "Using the default document class, because the "
459                                         " class %1$s could not be loaded.", theclass));
460                         params().textclass = 0;
461                 }
462         } else {
463                 // We don't want to adopt the parameters from the
464                 // document we insert, so read them into a temporary buffer
465                 // and then discard it
466
467                 Buffer tmpbuf("", false);
468                 tmpbuf.readHeader(lex);
469         }
470
471         return text().read(*this, lex);
472 }
473
474
475 // needed to insert the selection
476 void Buffer::insertStringAsLines(ParagraphList & pars,
477         par_type & par, pos_type & pos,
478         LyXFont const & fn, string const & str)
479 {
480         LyXLayout_ptr const & layout = pars[par].layout();
481
482         LyXFont font = fn;
483
484         pars[par].checkInsertChar(font);
485         // insert the string, don't insert doublespace
486         bool space_inserted = true;
487         bool autobreakrows = pars[par].autoBreakRows();
488         for (string::const_iterator cit = str.begin();
489             cit != str.end(); ++cit) {
490                 if (*cit == '\n') {
491                         if (autobreakrows && (!pars[par].empty() || pars[par].allowEmpty())) {
492                                 breakParagraph(params(), paragraphs(), par, pos,
493                                                layout->isEnvironment());
494                                 ++par;
495                                 pos = 0;
496                                 space_inserted = true;
497                         } else {
498                                 continue;
499                         }
500                         // do not insert consecutive spaces if !free_spacing
501                 } else if ((*cit == ' ' || *cit == '\t') &&
502                            space_inserted && !pars[par].isFreeSpacing()) {
503                         continue;
504                 } else if (*cit == '\t') {
505                         if (!pars[par].isFreeSpacing()) {
506                                 // tabs are like spaces here
507                                 pars[par].insertChar(pos, ' ', font);
508                                 ++pos;
509                                 space_inserted = true;
510                         } else {
511                                 const pos_type n = 8 - pos % 8;
512                                 for (pos_type i = 0; i < n; ++i) {
513                                         pars[par].insertChar(pos, ' ', font);
514                                         ++pos;
515                                 }
516                                 space_inserted = true;
517                         }
518                 } else if (!IsPrintable(*cit)) {
519                         // Ignore unprintables
520                         continue;
521                 } else {
522                         // just insert the character
523                         pars[par].insertChar(pos, *cit, font);
524                         ++pos;
525                         space_inserted = (*cit == ' ');
526                 }
527
528         }
529 }
530
531
532 bool Buffer::readFile(string const & filename)
533 {
534         // Check if the file is compressed.
535         string const format = getExtFromContents(filename);
536         if (format == "gzip" || format == "zip" || format == "compress") {
537                 params().compressed = true;
538         }
539
540         // remove dummy empty par
541         paragraphs().clear();
542         bool ret = readFile(filename, paragraphs().size());
543
544         // After we have read a file, we must ensure that the buffer
545         // language is set and used in the gui.
546         // If you know of a better place to put this, please tell me. (Lgb)
547         updateDocLang(params().language);
548
549         return ret;
550 }
551
552
553 bool Buffer::readFile(string const & filename, par_type pit)
554 {
555         LyXLex lex(0, 0);
556         lex.setFile(filename);
557         return readFile(lex, filename, pit);
558 }
559
560
561 bool Buffer::fully_loaded() const
562 {
563         return pimpl_->file_fully_loaded;
564 }
565
566
567 void Buffer::fully_loaded(bool value)
568 {
569         pimpl_->file_fully_loaded = value;
570 }
571
572
573 bool Buffer::readFile(LyXLex & lex, string const & filename, par_type pit)
574 {
575         BOOST_ASSERT(!filename.empty());
576
577         if (!lex.isOK()) {
578                 Alert::error(_("Document could not be read"),
579                              bformat(_("%1$s could not be read."), filename));
580                 return false;
581         }
582
583         lex.next();
584         string const token(lex.getString());
585
586         if (!lex.isOK()) {
587                 Alert::error(_("Document could not be read"),
588                              bformat(_("%1$s could not be read."), filename));
589                 return false;
590         }
591
592         // the first token _must_ be...
593         if (token != "\\lyxformat") {
594                 lyxerr << "Token: " << token << endl;
595
596                 Alert::error(_("Document format failure"),
597                              bformat(_("%1$s is not a LyX document."),
598                                        filename));
599                 return false;
600         }
601
602         lex.next();
603         string tmp_format = lex.getString();
604         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
605         // if present remove ".," from string.
606         string::size_type dot = tmp_format.find_first_of(".,");
607         //lyxerr << "           dot found at " << dot << endl;
608         if (dot != string::npos)
609                         tmp_format.erase(dot, 1);
610         int file_format = strToInt(tmp_format);
611         //lyxerr << "format: " << file_format << endl;
612
613         if (file_format != LYX_FORMAT) {
614                 string const tmpfile = tempName();
615                 if (tmpfile.empty()) {
616                         Alert::error(_("Conversion failed"),
617                                      bformat(_("%1$s is from an earlier"
618                                               " version of LyX, but a temporary"
619                                               " file for converting it could"
620                                               " not be created."),
621                                               filename));
622                         return false;
623                 }
624                 string command = LibFileSearch("lyx2lyx", "lyx2lyx");
625                 if (command.empty()) {
626                         Alert::error(_("Conversion script not found"),
627                                      bformat(_("%1$s is from an earlier"
628                                                " version of LyX, but the"
629                                                " conversion script lyx2lyx"
630                                                " could not be found."),
631                                                filename));
632                         return false;
633                 }
634                 command += " -t"
635                         + tostr(LYX_FORMAT)
636                         + " -o " + tmpfile + ' '
637                         + QuoteName(filename);
638                 lyxerr[Debug::INFO] << "Running '"
639                                     << command << '\''
640                                     << endl;
641                 cmd_ret const ret = RunCommand(command);
642                 if (ret.first != 0) {
643                         Alert::error(_("Conversion script failed"),
644                                      bformat(_("%1$s is from an earlier version"
645                                               " of LyX, but the lyx2lyx script"
646                                               " failed to convert it."),
647                                               filename));
648                         return false;
649                 } else {
650                         bool ret = readFile(tmpfile, pit);
651                         // Do stuff with tmpfile name and buffer name here.
652                         return ret;
653                 }
654
655         }
656
657         if (readDocument(lex)) {
658                 Alert::error(_("Document format failure"),
659                              bformat(_("%1$s ended unexpectedly, which means"
660                                        " that it is probably corrupted."),
661                                        filename));
662         }
663
664         //lyxerr << "removing " << MacroTable::localMacros().size()
665         //      << " temporary macro entries" << endl;
666         //MacroTable::localMacros().clear();
667         params().setPaperStuff();
668
669         pimpl_->file_fully_loaded = true;
670         return true;
671 }
672
673
674 // Should probably be moved to somewhere else: BufferView? LyXView?
675 bool Buffer::save() const
676 {
677         // We don't need autosaves in the immediate future. (Asger)
678         resetAutosaveTimers();
679
680         // make a backup
681         string s;
682         if (lyxrc.make_backup) {
683                 s = fileName() + '~';
684                 if (!lyxrc.backupdir_path.empty())
685                         s = AddName(lyxrc.backupdir_path,
686                                     subst(os::slashify_path(s),'/','!'));
687
688                 // Rename is the wrong way of making a backup,
689                 // this is the correct way.
690                 /* truss cp fil fil2:
691                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
692                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
693                    open("LyXVC.lyx", O_RDONLY)                     = 3
694                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
695                    fstat(4, 0xEFFFF508)                            = 0
696                    fstat(3, 0xEFFFF508)                            = 0
697                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
698                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
699                    read(3, 0xEFFFD4A0, 8192)                       = 0
700                    close(4)                                        = 0
701                    close(3)                                        = 0
702                    chmod("LyXVC3.lyx", 0100644)                    = 0
703                    lseek(0, 0, SEEK_CUR)                           = 46440
704                    _exit(0)
705                 */
706
707                 // Should probably have some more error checking here.
708                 // Doing it this way, also makes the inodes stay the same.
709                 // This is still not a very good solution, in particular we
710                 // might loose the owner of the backup.
711                 FileInfo finfo(fileName());
712                 if (finfo.exist()) {
713                         mode_t fmode = finfo.getMode();
714                         struct utimbuf times = {
715                                 finfo.getAccessTime(),
716                                 finfo.getModificationTime() };
717
718                         ifstream ifs(fileName().c_str());
719                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
720                         if (ifs && ofs) {
721                                 ofs << ifs.rdbuf();
722                                 ifs.close();
723                                 ofs.close();
724                                 ::chmod(s.c_str(), fmode);
725
726                                 if (::utime(s.c_str(), &times)) {
727                                         lyxerr << "utime error." << endl;
728                                 }
729                         } else {
730                                 lyxerr << "LyX was not able to make "
731                                         "backup copy. Beware." << endl;
732                         }
733                 }
734         }
735
736         if (writeFile(fileName())) {
737                 markClean();
738                 removeAutosaveFile(fileName());
739         } else {
740                 // Saving failed, so backup is not backup
741                 if (lyxrc.make_backup)
742                         rename(s, fileName());
743                 return false;
744         }
745         return true;
746 }
747
748
749 bool Buffer::writeFile(string const & fname) const
750 {
751         if (pimpl_->read_only && fname == fileName())
752                 return false;
753
754         FileInfo finfo(fname);
755         if (finfo.exist() && !finfo.writable())
756                 return false;
757
758         bool retval = false;
759
760         if (params().compressed) {
761                 gz::ogzstream ofs(fname.c_str());
762                 if (!ofs)
763                         return false;
764
765                 retval = do_writeFile(ofs);
766
767         } else {
768                 ofstream ofs(fname.c_str());
769                 if (!ofs)
770                         return false;
771
772                 retval = do_writeFile(ofs);
773         }
774
775         return retval;
776 }
777
778
779 bool Buffer::do_writeFile(ostream & ofs) const
780 {
781 #ifdef HAVE_LOCALE
782         // Use the standard "C" locale for file output.
783         ofs.imbue(std::locale::classic());
784 #endif
785
786         // The top of the file should not be written by params().
787
788         // write out a comment in the top of the file
789         ofs << "#LyX " << lyx_version
790             << " created this file. For more info see http://www.lyx.org/\n"
791             << "\\lyxformat " << LYX_FORMAT << "\n"
792             << "\\begin_document\n";
793
794         // now write out the buffer parameters.
795         ofs << "\n\\begin_header\n";
796         params().writeFile(ofs);
797         ofs << "\\end_header\n";
798         
799         // write the text
800         ofs << "\n\\begin_body\n";
801         text().write(*this, ofs);
802         ofs << "\n\\end_body\n";
803
804         // Write marker that shows file is complete
805         ofs << "\\end_document" << endl;
806
807         // Shouldn't really be needed....
808         //ofs.close();
809
810         // how to check if close went ok?
811         // Following is an attempt... (BE 20001011)
812
813         // good() returns false if any error occured, including some
814         //        formatting error.
815         // bad()  returns true if something bad happened in the buffer,
816         //        which should include file system full errors.
817
818         bool status = true;
819         if (!ofs) {
820                 status = false;
821                 lyxerr << "File was not closed properly." << endl;
822         }
823
824         return status;
825 }
826
827
828 void Buffer::makeLaTeXFile(string const & fname,
829                            string const & original_path,
830                            OutputParams const & runparams,
831                            bool output_preamble, bool output_body)
832 {
833         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
834
835         ofstream ofs;
836         if (!openFileWrite(ofs, fname))
837                 return;
838
839         makeLaTeXFile(ofs, original_path,
840                       runparams, output_preamble, output_body);
841
842         ofs.close();
843         if (ofs.fail())
844                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
845 }
846
847
848 void Buffer::makeLaTeXFile(ostream & os,
849                            string const & original_path,
850                            OutputParams const & runparams_in,
851                            bool output_preamble, bool output_body)
852 {
853         OutputParams runparams = runparams_in;
854
855         // validate the buffer.
856         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
857         LaTeXFeatures features(*this, params(), runparams.nice);
858         validate(features);
859         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
860
861         texrow().reset();
862
863         // The starting paragraph of the coming rows is the
864         // first paragraph of the document. (Asger)
865         texrow().start(paragraphs().begin()->id(), 0);
866
867         if (output_preamble && runparams.nice) {
868                 os << "%% LyX " << lyx_version << " created this file.  "
869                         "For more info, see http://www.lyx.org/.\n"
870                         "%% Do not edit unless you really know what "
871                         "you are doing.\n";
872                 texrow().newline();
873                 texrow().newline();
874         }
875         lyxerr[Debug::INFO] << "lyx header finished" << endl;
876         // There are a few differences between nice LaTeX and usual files:
877         // usual is \batchmode and has a
878         // special input@path to allow the including of figures
879         // with either \input or \includegraphics (what figinsets do).
880         // input@path is set when the actual parameter
881         // original_path is set. This is done for usual tex-file, but not
882         // for nice-latex-file. (Matthias 250696)
883         // Note that input@path is only needed for something the user does
884         // in the preamble, included .tex files or ERT, files included by
885         // LyX work without it.
886         if (output_preamble) {
887                 if (!runparams.nice) {
888                         // code for usual, NOT nice-latex-file
889                         os << "\\batchmode\n"; // changed
890                         // from \nonstopmode
891                         texrow().newline();
892                 }
893                 if (!original_path.empty()) {
894                         string inputpath = os::external_path(original_path);
895                         subst(inputpath, "~", "\\string~");
896                         os << "\\makeatletter\n"
897                             << "\\def\\input@path{{"
898                             << inputpath << "/}}\n"
899                             << "\\makeatother\n";
900                         texrow().newline();
901                         texrow().newline();
902                         texrow().newline();
903                 }
904
905                 // Write the preamble
906                 runparams.use_babel = params().writeLaTeX(os, features, texrow());
907
908                 if (!output_body)
909                         return;
910
911                 // make the body.
912                 os << "\\begin{document}\n";
913                 texrow().newline();
914         } // output_preamble
915         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
916
917         if (!lyxrc.language_auto_begin) {
918                 os << subst(lyxrc.language_command_begin, "$$lang",
919                              params().language->babel())
920                     << endl;
921                 texrow().newline();
922         }
923
924         // if we are doing a real file with body, even if this is the
925         // child of some other buffer, let's cut the link here.
926         // This happens for example if only a child document is printed.
927         string save_parentname;
928         if (output_preamble) {
929                 save_parentname = params().parentname;
930                 params().parentname.erase();
931         }
932
933         // the real stuff
934         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
935
936         // Restore the parenthood if needed
937         if (output_preamble)
938                 params().parentname = save_parentname;
939
940         // add this just in case after all the paragraphs
941         os << endl;
942         texrow().newline();
943
944         if (!lyxrc.language_auto_end) {
945                 os << subst(lyxrc.language_command_end, "$$lang",
946                              params().language->babel())
947                     << endl;
948                 texrow().newline();
949         }
950
951         if (output_preamble) {
952                 os << "\\end{document}\n";
953                 texrow().newline();
954
955                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
956         } else {
957                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
958                                      << endl;
959         }
960
961         // Just to be sure. (Asger)
962         texrow().newline();
963
964         lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
965         lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
966                             << '.' << endl;
967 }
968
969
970 bool Buffer::isLatex() const
971 {
972         return params().getLyXTextClass().outputType() == LATEX;
973 }
974
975
976 bool Buffer::isLinuxDoc() const
977 {
978         return params().getLyXTextClass().outputType() == LINUXDOC;
979 }
980
981
982 bool Buffer::isLiterate() const
983 {
984         return params().getLyXTextClass().outputType() == LITERATE;
985 }
986
987
988 bool Buffer::isDocBook() const
989 {
990         return params().getLyXTextClass().outputType() == DOCBOOK;
991 }
992
993
994 bool Buffer::isSGML() const
995 {
996         LyXTextClass const & tclass = params().getLyXTextClass();
997
998         return tclass.outputType() == LINUXDOC ||
999                tclass.outputType() == DOCBOOK;
1000 }
1001
1002
1003 void Buffer::makeLinuxDocFile(string const & fname,
1004                               OutputParams const & runparams,
1005                               bool body_only)
1006 {
1007         ofstream ofs;
1008         if (!openFileWrite(ofs, fname))
1009                 return;
1010
1011         LaTeXFeatures features(*this, params(), runparams.nice);
1012         validate(features);
1013
1014         texrow().reset();
1015
1016         LyXTextClass const & tclass = params().getLyXTextClass();
1017
1018         string top_element = tclass.latexname();
1019
1020         if (!body_only) {
1021                 ofs << tclass.class_header();
1022
1023                 string preamble = params().preamble;
1024                 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1025                          : fname;
1026                 preamble += features.getIncludedFiles(name);
1027                 preamble += features.getLyXSGMLEntities();
1028
1029                 if (!preamble.empty()) {
1030                         ofs << " [ " << preamble << " ]";
1031                 }
1032                 ofs << ">\n\n";
1033
1034                 if (params().options.empty())
1035                         sgml::openTag(ofs, 0, false, top_element);
1036                 else {
1037                         string top = top_element;
1038                         top += ' ';
1039                         top += params().options;
1040                         sgml::openTag(ofs, 0, false, top);
1041                 }
1042         }
1043
1044         ofs << "<!-- LyX "  << lyx_version
1045             << " created this file. For more info see http://www.lyx.org/"
1046             << " -->\n";
1047
1048         linuxdocParagraphs(*this, paragraphs(), ofs, runparams);
1049
1050         if (!body_only) {
1051                 ofs << "\n\n";
1052                 sgml::closeTag(ofs, 0, false, top_element);
1053         }
1054
1055         ofs.close();
1056         if (ofs.fail())
1057                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1058 }
1059
1060
1061 void Buffer::makeDocBookFile(string const & fname,
1062                              OutputParams const & runparams,
1063                              bool only_body)
1064 {
1065         ofstream ofs;
1066         if (!openFileWrite(ofs, fname))
1067                 return;
1068
1069         LaTeXFeatures features(*this, params(), runparams.nice);
1070         validate(features);
1071
1072         texrow().reset();
1073
1074         LyXTextClass const & tclass = params().getLyXTextClass();
1075         string top_element = tclass.latexname();
1076
1077         if (!only_body) {
1078                 if (runparams.flavor == OutputParams::XML)
1079                         ofs << "<?xml version=\"1.0\" encoding=\""
1080                             << params().language->encoding()->Name() << "\"?>\n";
1081
1082                 ofs << "<!DOCTYPE " << top_element << " ";
1083
1084                 if (! tclass.class_header().empty()) ofs << tclass.class_header();
1085                 else if (runparams.flavor == OutputParams::XML)
1086                         ofs << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1087                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1088                 else
1089                         ofs << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1090
1091                 string preamble = params().preamble;
1092                 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1093                          : fname;
1094                 preamble += features.getIncludedFiles(name);
1095                 preamble += features.getLyXSGMLEntities();
1096
1097                 if (!preamble.empty()) {
1098                         ofs << "\n [ " << preamble << " ]";
1099                 }
1100                 ofs << ">\n\n";
1101         }
1102
1103         string top = top_element;
1104         top += " lang=\"";
1105         if (runparams.flavor == OutputParams::XML)
1106                 top += params().language->code();
1107         else
1108                 top += params().language->code().substr(0,2);
1109         top += '"';
1110
1111         if (!params().options.empty()) {
1112                 top += ' ';
1113                 top += params().options;
1114         }
1115         sgml::openTag(ofs, 0, false, top);
1116
1117         ofs << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1118             << " file was created by LyX " << lyx_version
1119             << "\n  See http://www.lyx.org/ for more information -->\n";
1120
1121         params().getLyXTextClass().counters().reset();
1122         docbookParagraphs(*this, paragraphs(), ofs, runparams);
1123
1124         ofs << "\n\n";
1125         sgml::closeTag(ofs, 0, false, top_element);
1126
1127         ofs.close();
1128         if (ofs.fail())
1129                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1130 }
1131
1132
1133 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1134 // Other flags: -wall -v0 -x
1135 int Buffer::runChktex()
1136 {
1137         busy(true);
1138
1139         // get LaTeX-Filename
1140         string const name = getLatexName();
1141         string const path = temppath();
1142         string const org_path = filePath();
1143
1144         Path p(path); // path to LaTeX file
1145         message(_("Running chktex..."));
1146
1147         // Generate the LaTeX file if neccessary
1148         OutputParams runparams;
1149         runparams.flavor = OutputParams::LATEX;
1150         runparams.nice = false;
1151         makeLaTeXFile(name, org_path, runparams);
1152
1153         TeXErrors terr;
1154         Chktex chktex(lyxrc.chktex_command, name, filePath());
1155         int res = chktex.run(terr); // run chktex
1156
1157         if (res == -1) {
1158                 Alert::error(_("chktex failure"),
1159                              _("Could not run chktex successfully."));
1160         } else if (res > 0) {
1161                 // Insert all errors as errors boxes
1162                 bufferErrors(*this, terr);
1163         }
1164
1165         busy(false);
1166
1167         return res;
1168 }
1169
1170
1171 void Buffer::validate(LaTeXFeatures & features) const
1172 {
1173         LyXTextClass const & tclass = params().getLyXTextClass();
1174
1175         if (params().tracking_changes) {
1176                 features.require("dvipost");
1177                 features.require("color");
1178         }
1179
1180         // AMS Style is at document level
1181         if (params().use_amsmath == BufferParams::AMS_ON
1182             || tclass.provides(LyXTextClass::amsmath))
1183                 features.require("amsmath");
1184
1185         for_each(paragraphs().begin(), paragraphs().end(),
1186                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1187
1188         // the bullet shapes are buffer level not paragraph level
1189         // so they are tested here
1190         for (int i = 0; i < 4; ++i) {
1191                 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1192                         int const font = params().user_defined_bullet(i).getFont();
1193                         if (font == 0) {
1194                                 int const c = params()
1195                                         .user_defined_bullet(i)
1196                                         .getCharacter();
1197                                 if (c == 16
1198                                    || c == 17
1199                                    || c == 25
1200                                    || c == 26
1201                                    || c == 31) {
1202                                         features.require("latexsym");
1203                                 }
1204                         } else if (font == 1) {
1205                                 features.require("amssymb");
1206                         } else if ((font >= 2 && font <= 5)) {
1207                                 features.require("pifont");
1208                         }
1209                 }
1210         }
1211
1212         if (lyxerr.debugging(Debug::LATEX)) {
1213                 features.showStruct();
1214         }
1215 }
1216
1217
1218 void Buffer::getLabelList(std::vector<string> & list) const
1219 {
1220         /// if this is a child document and the parent is already loaded
1221         /// Use the parent's list instead  [ale990407]
1222         Buffer const * tmp = getMasterBuffer();
1223         if (!tmp) {
1224                 lyxerr << "getMasterBuffer() failed!" << endl;
1225                 BOOST_ASSERT(tmp);
1226         }
1227         if (tmp != this) {
1228                 tmp->getLabelList(list);
1229                 return;
1230         }
1231
1232         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1233                 it.nextInset()->getLabelList(*this, list);
1234 }
1235
1236
1237 // This is also a buffer property (ale)
1238 void Buffer::fillWithBibKeys(std::vector<std::pair<string, string> > & keys)
1239         const
1240 {
1241         /// if this is a child document and the parent is already loaded
1242         /// use the parent's list instead  [ale990412]
1243         Buffer const * tmp = getMasterBuffer();
1244         BOOST_ASSERT(tmp);
1245         if (tmp != this) {
1246                 tmp->fillWithBibKeys(keys);
1247                 return;
1248         }
1249
1250         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1251                 if (it->lyxCode() == InsetOld::BIBTEX_CODE) {
1252                         InsetBibtex const & inset =
1253                                 dynamic_cast<InsetBibtex const &>(*it);
1254                         inset.fillWithBibKeys(*this, keys);
1255                 } else if (it->lyxCode() == InsetOld::INCLUDE_CODE) {
1256                         InsetInclude const & inset =
1257                                 dynamic_cast<InsetInclude const &>(*it);
1258                         inset.fillWithBibKeys(*this, keys);
1259                 } else if (it->lyxCode() == InsetOld::BIBITEM_CODE) {
1260                         InsetBibitem const & inset =
1261                                 dynamic_cast<InsetBibitem const &>(*it);
1262                         string const key = inset.getContents();
1263                         string const opt = inset.getOptions();
1264                         string const ref; // = pit->asString(this, false);
1265                         string const info = opt + "TheBibliographyRef" + ref;
1266                         keys.push_back(pair<string, string>(key, info));
1267                 }
1268         }
1269 }
1270
1271
1272 bool Buffer::isDepClean(string const & name) const
1273 {
1274         DepClean::const_iterator it = pimpl_->dep_clean.find(name);
1275         if (it == pimpl_->dep_clean.end())
1276                 return true;
1277         return it->second;
1278 }
1279
1280
1281 void Buffer::markDepClean(string const & name)
1282 {
1283         pimpl_->dep_clean[name] = true;
1284 }
1285
1286
1287 bool Buffer::dispatch(string const & command, bool * result)
1288 {
1289         return dispatch(lyxaction.lookupFunc(command), result);
1290 }
1291
1292
1293 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1294 {
1295         bool dispatched = true;
1296
1297         switch (func.action) {
1298                 case LFUN_EXPORT: {
1299                         bool const tmp = Exporter::Export(this, func.argument, false);
1300                         if (result)
1301                                 *result = tmp;
1302                         break;
1303                 }
1304
1305                 default:
1306                         dispatched = false;
1307         }
1308         return dispatched;
1309 }
1310
1311
1312 void Buffer::changeLanguage(Language const * from, Language const * to)
1313 {
1314         lyxerr << "Changing Language!" << endl;
1315
1316         // Take care of l10n/i18n
1317         updateDocLang(to);
1318
1319         ParIterator end = par_iterator_end();
1320         for (ParIterator it = par_iterator_begin(); it != end; ++it)
1321                 it->changeLanguage(params(), from, to);
1322 }
1323
1324
1325 void Buffer::updateDocLang(Language const * nlang)
1326 {
1327         pimpl_->messages.reset(new Messages(nlang->code()));
1328 }
1329
1330
1331 bool Buffer::isMultiLingual() const
1332 {
1333         ParConstIterator end = par_iterator_end();
1334         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1335                 if (it->isMultiLingual(params()))
1336                         return true;
1337
1338         return false;
1339 }
1340
1341
1342 ParIterator Buffer::getParFromID(int id) const
1343 {
1344         ParConstIterator it = par_iterator_begin();
1345         ParConstIterator end = par_iterator_end();
1346
1347         if (id < 0) {
1348                 // John says this is called with id == -1 from undo
1349                 lyxerr << "getParFromID(), id: " << id << endl;
1350                 return end;
1351         }
1352
1353         for (; it != end; ++it)
1354                 if (it->id() == id)
1355                         return it;
1356
1357         return end;
1358 }
1359
1360
1361 bool Buffer::hasParWithID(int id) const
1362 {
1363         ParConstIterator it = par_iterator_begin();
1364         ParConstIterator end = par_iterator_end();
1365
1366         if (id < 0) {
1367                 // John says this is called with id == -1 from undo
1368                 lyxerr << "hasParWithID(), id: " << id << endl;
1369                 return 0;
1370         }
1371
1372         for (; it != end; ++it)
1373                 if (it->id() == id)
1374                         return true;
1375
1376         return false;
1377 }
1378
1379
1380 ParIterator Buffer::par_iterator_begin()
1381 {
1382         return ::par_iterator_begin(inset());
1383 }
1384
1385
1386 ParIterator Buffer::par_iterator_end()
1387 {
1388         return ::par_iterator_end(inset());
1389 }
1390
1391
1392 ParConstIterator Buffer::par_iterator_begin() const
1393 {
1394         return ::par_const_iterator_begin(inset());
1395 }
1396
1397
1398 ParConstIterator Buffer::par_iterator_end() const
1399 {
1400         return ::par_const_iterator_end(inset());
1401 }
1402
1403
1404 Language const * Buffer::getLanguage() const
1405 {
1406         return params().language;
1407 }
1408
1409
1410 string const Buffer::B_(string const & l10n) const
1411 {
1412         if (pimpl_->messages.get()) {
1413                 return pimpl_->messages->get(l10n);
1414         }
1415
1416         return _(l10n);
1417 }
1418
1419
1420 bool Buffer::isClean() const
1421 {
1422         return pimpl_->lyx_clean;
1423 }
1424
1425
1426 bool Buffer::isBakClean() const
1427 {
1428         return pimpl_->bak_clean;
1429 }
1430
1431
1432 void Buffer::markClean() const
1433 {
1434         if (!pimpl_->lyx_clean) {
1435                 pimpl_->lyx_clean = true;
1436                 updateTitles();
1437         }
1438         // if the .lyx file has been saved, we don't need an
1439         // autosave
1440         pimpl_->bak_clean = true;
1441 }
1442
1443
1444 void Buffer::markBakClean()
1445 {
1446         pimpl_->bak_clean = true;
1447 }
1448
1449
1450 void Buffer::setUnnamed(bool flag)
1451 {
1452         pimpl_->unnamed = flag;
1453 }
1454
1455
1456 bool Buffer::isUnnamed() const
1457 {
1458         return pimpl_->unnamed;
1459 }
1460
1461
1462 void Buffer::markDirty()
1463 {
1464         if (pimpl_->lyx_clean) {
1465                 pimpl_->lyx_clean = false;
1466                 updateTitles();
1467         }
1468         pimpl_->bak_clean = false;
1469
1470         DepClean::iterator it = pimpl_->dep_clean.begin();
1471         DepClean::const_iterator const end = pimpl_->dep_clean.end();
1472
1473         for (; it != end; ++it) {
1474                 it->second = false;
1475         }
1476 }
1477
1478
1479 string const & Buffer::fileName() const
1480 {
1481         return pimpl_->filename;
1482 }
1483
1484
1485 string const & Buffer::filePath() const
1486 {
1487         return pimpl_->filepath;
1488 }
1489
1490
1491 bool Buffer::isReadonly() const
1492 {
1493         return pimpl_->read_only;
1494 }
1495
1496
1497 void Buffer::setParentName(string const & name)
1498 {
1499         params().parentname = name;
1500 }
1501
1502
1503 Buffer const * Buffer::getMasterBuffer() const
1504 {
1505         if (!params().parentname.empty()
1506             && bufferlist.exists(params().parentname)) {
1507                 Buffer const * buf = bufferlist.getBuffer(params().parentname);
1508                 if (buf)
1509                         return buf->getMasterBuffer();
1510         }
1511
1512         return this;
1513 }
1514
1515
1516 MacroData const & Buffer::getMacro(std::string const & name) const
1517 {
1518         return pimpl_->macros.get(name);
1519 }
1520
1521
1522 bool Buffer::hasMacro(string const & name) const
1523 {
1524         return pimpl_->macros.has(name);
1525 }
1526
1527
1528 void Buffer::insertMacro(string const & name, MacroData const & data)
1529 {
1530         MacroTable::globalMacros().insert(name, data);
1531         pimpl_->macros.insert(name, data);
1532 }
1533
1534
1535 void Buffer::buildMacros()
1536 {
1537         // Start with global table.
1538         pimpl_->macros = MacroTable::globalMacros();
1539
1540         // Now add our own.
1541         ParagraphList & pars = text().paragraphs();
1542         for (size_t i = 0, n = pars.size(); i != n; ++i) {
1543                 //lyxerr << "searching main par " << i
1544                 //      << " for macro definitions" << std::endl;
1545                 InsetList::iterator it = pars[i].insetlist.begin();
1546                 InsetList::iterator end = pars[i].insetlist.end();
1547                 for ( ; it != end; ++it) {
1548                         //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1549                         if (it->inset->lyxCode() == InsetBase::MATHMACRO_CODE) {
1550                                 MathMacroTemplate & mac
1551                                         = static_cast<MathMacroTemplate &>(*it->inset);
1552                                 insertMacro(mac.name(), mac.asMacroData());
1553                         }
1554                 }
1555         }
1556 }