]> git.lyx.org Git - lyx.git/blob - src/Buffer.h
Improve fullscreen capabilities ( http://bugzilla.lyx.org/show_bug.cgi?id=4146 ).
[lyx.git] / src / Buffer.h
1 // -*- C++ -*-
2 /**
3  * \file Buffer.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Lars Gullik Bjønnes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #ifndef BUFFER_H
13 #define BUFFER_H
14
15 #include "insets/InsetCode.h"
16
17 #include "support/strfwd.h"
18 #include "support/types.h"
19 #include "support/SignalSlot.h"
20
21 #include <set>
22 #include <string>
23 #include <vector>
24
25
26 namespace lyx {
27
28 class BufferParams;
29 class EmbeddedFileList;
30 class DocIterator;
31 class ErrorItem;
32 class ErrorList;
33 class FuncRequest;
34 class Inset;
35 class Font;
36 class Format;
37 class Lexer;
38 class LyXRC;
39 class Text;
40 class LyXVC;
41 class LaTeXFeatures;
42 class Language;
43 class MacroData;
44 class OutputParams;
45 class Paragraph;
46 class ParConstIterator;
47 class ParIterator;
48 class ParagraphList;
49 class TeXErrors;
50 class TexRow;
51 class TocBackend;
52 class Undo;
53
54 namespace frontend {
55 class GuiBufferDelegate;
56 class WorkAreaManager;
57 }
58
59 namespace support {
60 class FileName;
61 }
62
63 /** The buffer object.
64  * This is the buffer object. It contains all the informations about
65  * a document loaded into LyX.
66  * The buffer object owns the Text (wrapped in an InsetText), which
67  * contains the individual paragraphs of the document.
68  *
69  *
70  * I am not sure if the class is complete or
71  * minimal, probably not.
72  * \author Lars Gullik Bjønnes
73  */
74 class Buffer {
75 public:
76         /// What type of log will \c getLogName() return?
77         enum LogType {
78                 latexlog, ///< LaTeX log
79                 buildlog  ///< Literate build log
80         };
81
82         /// Result of \c readFile()
83         enum ReadStatus {
84                 failure, ///< The file could not be read
85                 success, ///< The file could not be read
86                 wrongversion ///< The version of the file does not match ours
87         };
88
89
90         /// Method to check if a file is externally modified, used by 
91         /// isExternallyModified()
92         /**
93          * timestamp is fast but inaccurate. For example, the granularity
94          * of timestamp on a FAT filesystem is 2 second. Also, various operations
95          * may touch the timestamp of a file even when its content is unchanged.
96          *
97          * checksum is accurate but slow, which can be a problem when it is 
98          * frequently used, or used for a large file on a slow (network) file
99          * system.
100          *
101          * FIXME: replace this method with support/FileMonitor.
102          */
103         enum CheckMethod {
104                 checksum_method,  ///< Use file checksum
105                 timestamp_method, ///< Use timestamp, and checksum if timestamp has changed
106         };
107         
108         /** Constructor
109             \param file
110             \param b  optional \c false by default
111         */
112         explicit Buffer(std::string const & file, bool b = false);
113
114         /// Destructor
115         ~Buffer();
116
117         /** High-level interface to buffer functionality.
118             This function parses a command string and executes it
119         */
120         bool dispatch(std::string const & command, bool * result = 0);
121
122         /// Maybe we know the function already by number...
123         bool dispatch(FuncRequest const & func, bool * result = 0);
124
125         /// Load the autosaved file.
126         void loadAutoSaveFile();
127
128         /// read a new document from a string
129         bool readString(std::string const &);
130         /// load a new file
131         bool readFile(support::FileName const & filename);
132
133         /// read the header, returns number of unknown tokens
134         int readHeader(Lexer & lex);
135
136         /** Reads a file without header.
137             \param par if != 0 insert the file.
138             \return \c false if file is not completely read.
139         */
140         bool readDocument(Lexer &);
141
142         ///
143         void insertStringAsLines(ParagraphList & plist,
144                 pit_type &, pos_type &,
145                 Font const &, docstring const &, bool);
146         ///
147         ParIterator getParFromID(int id);
148         ///
149         ParConstIterator getParFromID(int id) const;
150         /// do we have a paragraph with this id?
151         bool hasParWithID(int id) const;
152
153         ///
154         frontend::WorkAreaManager & workAreaManager() const;
155
156         /** Save file.
157             Takes care of auto-save files and backup file if requested.
158             Returns \c true if the save is successful, \c false otherwise.
159         */
160         bool save() const;
161
162         /// Write document to stream. Returns \c false if unsuccesful.
163         bool write(std::ostream &) const;
164         /// Write file. Returns \c false if unsuccesful.
165         bool writeFile(support::FileName const &) const;
166
167   /// Loads LyX file \c filename into buffer, *  and \return success 
168         bool loadLyXFile(support::FileName const & s);
169
170         /// Fill in the ErrorList with the TeXErrors
171         void bufferErrors(TeXErrors const &, ErrorList &) const;
172
173         /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
174         bool makeLaTeXFile(support::FileName const & filename,
175                            std::string const & original_path,
176                            OutputParams const &,
177                            bool output_preamble = true,
178                            bool output_body = true) const;
179         /** Export the buffer to LaTeX.
180             If \p os is a file stream, and params().inputenc is "auto" or
181             "default", and the buffer contains text in different languages
182             with more than one encoding, then this method will change the
183             encoding associated to \p os. Therefore you must not call this
184             method with a string stream if the output is supposed to go to a
185             file. \code
186             odocfstream ofs;
187             ofs.open("test.tex");
188             writeLaTeXSource(ofs, ...);
189             ofs.close();
190             \endcode is NOT equivalent to \code
191             odocstringstream oss;
192             writeLaTeXSource(oss, ...);
193             odocfstream ofs;
194             ofs.open("test.tex");
195             ofs << oss.str();
196             ofs.close();
197             \endcode
198          */
199         void writeLaTeXSource(odocstream & os,
200                            std::string const & original_path,
201                            OutputParams const &,
202                            bool output_preamble = true,
203                            bool output_body = true) const;
204         ///
205         void makeDocBookFile(support::FileName const & filename,
206                              OutputParams const & runparams_in,
207                              bool only_body = false) const;
208         ///
209         void writeDocBookSource(odocstream & os, std::string const & filename,
210                              OutputParams const & runparams_in,
211                              bool only_body = false) const;
212         /// returns the main language for the buffer (document)
213         Language const * language() const;
214         /// get l10n translated to the buffers language
215         docstring const B_(std::string const & l10n) const;
216
217         ///
218         int runChktex();
219         /// return true if the main lyx file does not need saving
220         bool isClean() const;
221         ///
222         bool isBakClean() const;
223         ///
224         bool isDepClean(std::string const & name) const;
225
226         /// whether or not disk file has been externally modified
227         bool isExternallyModified(CheckMethod method) const;
228
229         /// save timestamp and checksum of the given file.
230         void saveCheckSum(support::FileName const & file) const;
231
232         /// mark the main lyx file as not needing saving
233         void markClean() const;
234
235         ///
236         void markBakClean() const;
237
238         ///
239         void markDepClean(std::string const & name);
240
241         ///
242         void setUnnamed(bool flag = true);
243
244         ///
245         bool isUnnamed() const;
246
247         /// Mark this buffer as dirty.
248         void markDirty();
249
250         /// Returns the buffer's filename. It is always an absolute path.
251         support::FileName fileName() const;
252
253         /// Returns the buffer's filename. It is always an absolute path.
254         std::string absFileName() const;
255
256         /// Returns the the path where the buffer lives.
257         /// It is always an absolute path.
258         std::string filePath() const;
259
260         /** A transformed version of the file name, adequate for LaTeX.
261             \param no_path optional if \c true then the path is stripped.
262         */
263         std::string latexName(bool no_path = true) const;
264
265         /// Get thee name and type of the log.
266         std::string logName(LogType * type = 0) const;
267
268         /// Change name of buffer. Updates "read-only" flag.
269         void setFileName(std::string const & newfile);
270
271         /// Set document's parent Buffer.
272         void setParent(Buffer const *);
273         Buffer const * parent();
274
275         /** Get the document's master (or \c this if this is not a
276             child document)
277          */
278         Buffer const * masterBuffer() const;
279
280         /// Is buffer read-only?
281         bool isReadonly() const;
282
283         /// Set buffer read-only flag
284         void setReadonly(bool flag = true);
285
286         /// returns \c true if the buffer contains a LaTeX document
287         bool isLatex() const;
288         /// returns \c true if the buffer contains a DocBook document
289         bool isDocBook() const;
290         /// returns \c true if the buffer contains a Wed document
291         bool isLiterate() const;
292
293         /** Validate a buffer for LaTeX.
294             This validates the buffer, and returns a struct for use by
295             #makeLaTeX# and others. Its main use is to figure out what
296             commands and packages need to be included in the LaTeX file.
297             It (should) also check that the needed constructs are there
298             (i.e. that the \refs points to coresponding \labels). It
299             should perhaps inset "error" insets to help the user correct
300             obvious mistakes.
301         */
302         void validate(LaTeXFeatures &) const;
303
304         /// Update the cache with all bibfiles in use (including bibfiles
305         /// of loaded child documents).
306         void updateBibfilesCache() const;
307         /// Return the cache with all bibfiles in use (including bibfiles
308         /// of loaded child documents).
309         EmbeddedFileList const & getBibfilesCache() const;
310         ///
311         void getLabelList(std::vector<docstring> &) const;
312
313         ///
314         void changeLanguage(Language const * from, Language const * to);
315
316         ///
317         bool isMultiLingual() const;
318
319         ///
320         BufferParams & params();
321         BufferParams const & params() const;
322
323         /** The list of paragraphs.
324             This is a linked list of paragraph, this list holds the
325             whole contents of the document.
326          */
327         ParagraphList & paragraphs();
328         ParagraphList const & paragraphs() const;
329
330         /// LyX version control object.
331         LyXVC & lyxvc();
332         LyXVC const & lyxvc() const;
333
334         /// Where to put temporary files.
335         std::string const temppath() const;
336
337         /// Used when typesetting to place errorboxes.
338         TexRow const & texrow() const;
339
340         ///
341         ParIterator par_iterator_begin();
342         ///
343         ParConstIterator par_iterator_begin() const;
344         ///
345         ParIterator par_iterator_end();
346         ///
347         ParConstIterator par_iterator_end() const;
348
349         /** \returns true only when the file is fully loaded.
350          *  Used to prevent the premature generation of previews
351          *  and by the citation inset.
352          */
353         bool isFullyLoaded() const;
354         /// Set by buffer_funcs' newFile.
355         void setFullyLoaded(bool);
356
357         /// Our main text (inside the top InsetText)
358         Text & text() const;
359
360         /// Our top InsetText
361         Inset & inset() const;
362
363         //
364         // Macro handling
365         //
366         /// Collect macro definitions in paragraphs
367         void updateMacros() const;
368         /// Iterate through the whole buffer and try to resolve macros
369         void updateMacroInstances() const;
370
371         typedef std::set<docstring> MacroNameSet;
372         /// List macro names of this buffer. the parent and the children
373         void listMacroNames(MacroNameSet & macros) const;
374         /// Write out all macros somewhere defined in the parent,
375         /// its parents and its children, which are visible at the beginning 
376         /// of this buffer
377         void writeParentMacros(odocstream & os) const;
378
379         /// Return macro defined before pos (or in the master buffer)
380         MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
381         /// Return macro defined anywhere in the buffer (or in the master buffer)
382         MacroData const * getMacro(docstring const & name, bool global = true) const;
383         /// Return macro defined before the inclusion of the child
384         MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
385
386         /// Replace the inset contents for insets which InsetCode is equal
387         /// to the passed \p inset_code.
388         void changeRefsIfUnique(docstring const & from, docstring const & to,
389                 InsetCode code);
390
391         /// get source code (latex/docbook) for some paragraphs, or all paragraphs
392         /// including preamble
393         void getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end,
394                 bool full_source);
395
396         /// Access to error list.
397         /// This method is used only for GUI visualisation of Buffer related
398         /// errors (like parsing or LateX compilation). This method is const
399         /// because modifying the returned ErrorList does not touch the document
400         /// contents.
401         ErrorList & errorList(std::string const & type) const;
402
403         /// The Toc backend.
404         /// This is useful only for screen visualisation of the Buffer. This
405         /// method is const because modifying this backend does not touch
406         /// the document contents.
407         TocBackend & tocBackend() const;
408         
409         //@{
410         EmbeddedFileList & embeddedFiles();
411         EmbeddedFileList const & embeddedFiles() const;
412         bool embedded() const;
413         //@}
414
415         Undo & undo();
416        
417         /// This function is called when the buffer is changed.
418         void changed() const;
419         /// This function is called when the buffer structure is changed.
420         void structureChanged() const;
421         /// This function is called when some parsing error shows up.
422         void errors(std::string const & err) const;
423         /// This function is called when the buffer busy status change.
424         void setBusy(bool on) const;
425         /// This function is called when the buffer readonly status change.
426         void setReadOnly(bool on) const;
427         /// Update window titles of all users.
428         void updateTitles() const;
429         /// Reset autosave timers for all users.
430         void resetAutosaveTimers() const;
431         ///
432         void message(docstring const & msg) const;
433
434         void setGuiDelegate(frontend::GuiBufferDelegate * gui);
435
436         ///
437         void autoSave() const;
438         ///
439         void loadChildDocuments() const;
440         ///
441         void resetChildDocuments(bool close_them) const;
442
443         /// return the format of the buffer on a string
444         std::string bufferFormat() const;
445
446         ///
447         bool doExport(std::string const & format, bool put_in_tempdir,
448                 std::string & result_file) const;
449         ///
450         bool doExport(std::string const & format, bool put_in_tempdir) const;
451         ///
452         bool preview(std::string const & format) const;
453         ///
454         bool isExportable(std::string const & format) const;
455         ///
456         std::vector<Format const *> exportableFormats(bool only_viewable) const;
457
458 private:
459         /// search for macro in local (buffer) table or in children
460         MacroData const * getBufferMacro(docstring const & name,
461                                          DocIterator const & pos) const;
462         /** Update macro table in the whole text inset
463             \param it at the start of the text inset)
464         */
465         void updateInsetMacros(DocIterator & it, 
466                                DocIterator & scope) const;
467         /** Update macro table for paragraphs until \c lastpit
468             \param it in some text inset
469             \param lastpit last processed paragraph
470         */
471         void updateEnvironmentMacros(DocIterator & it, 
472                                      pit_type lastpit, 
473                                      DocIterator & scope) const;
474         /** Update macro table for one paragraph block with 
475             same layout and depth, until \c lastpit
476             \param it in some text inset
477             \param lastpit last processed paragraph
478         */
479         void updateBlockMacros(DocIterator & it, 
480                                DocIterator & scope) const;
481
482         /// 
483         bool readFileHelper(support::FileName const & s);
484         ///
485         std::vector<std::string> backends() const;
486         /** Inserts a file into a document
487             \return \c false if method fails.
488         */
489         ReadStatus readFile(Lexer &, support::FileName const & filename,
490                             bool fromString = false);
491
492         /// Use the Pimpl idiom to hide the internals.
493         class Impl;
494         /// The pointer never changes although *pimpl_'s contents may.
495         Impl * const d;
496
497         frontend::GuiBufferDelegate * gui_;
498
499         /// This function is called when the buffer structure is changed.
500         Signal structureChanged_;
501         /// This function is called when some parsing error shows up.
502         //Signal errors(std::string const &) = 0;
503         /// This function is called when some message shows up.
504         //Signal message(docstring const &) = 0;
505         /// This function is called when the buffer busy status change.
506         //Signal setBusy(bool) = 0;
507         /// Reset autosave timers for all users.
508         Signal resetAutosaveTimers_;
509 };
510
511
512 } // namespace lyx
513
514 #endif