PyProTex.py 42.6 KB
Newer Older
1 2 3
#!/usr/bin/python
#
# Copyright 2014 Plymouth Marine Laboratory
4
#
Momme's avatar
Momme committed
5
# This file is free software: you can redistribute it and/or modify it
6 7
# under the terms of the Lesser GNU General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
8
# (at your option) any later version.
9
#
Momme's avatar
Momme committed
10
# It is distributed in the hope that it will be useful, but
11 12
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Lesser
13
# NU General Public License for more details.
14
# You should have received a copy of the Lesser GNU General Public License
Momme's avatar
Momme committed
15
# along with this copy. If not, see <http://www.gnu.org/licenses/>.
16
#
17 18 19 20
# Address:
# Plymouth Marine Laboratory
# Prospect Place, The Hoe
# Plymouth, PL1 3DH, UK
21
#
22 23 24 25 26 27 28 29 30 31
# Email:
# ssm@pml.ac.uk
#
#  $Id: PyProTex,v14.10 $
#
#BOP
#
# !ROUTINE: PyProTex - Translates DAO Prologues to LaTeX
#
# !INTERFACE:
32
#         PyProTex.py [-hbgACFS] ] [+-nlsxf] src_file[s]
33 34 35
#
# !DESCRIPTION:
#         This as a python version of the protex perl tool.
Momme Butenschoen's avatar
Momme Butenschoen committed
36
#         The perl tool was developed at the Goddard Space Flight Center
37 38 39 40 41
#         by Arlindo Da Silva, Will Sawyer, and others under no specific
#         license.
#         The python version was created by Momme Butenschoen at the
#         Plymouth Marine Laboratory
#         The adaptation is based on the version 2.0 as downloaded from
Momme Butenschoen's avatar
Momme Butenschoen committed
42
#         http://acmg.seas.harvard.edu/geos/wiki\_docs/protex/protex.tar.gz
43
#
44 45
#         Python class to produce a \LaTeX compatible document
#         from a DAO Fortran source code with standard Pro\TeX
46 47
#         prologues.
#         By default, output is directed to stdout.
48 49
#
# \noindent
50 51 52 53 54 55 56 57
# {\bf Command Line Switches:} \vspace{0.2cm}
#
# \begin{center}
# \begin{tabular}{|c|l|} \hline \hline
#   -h   & Human mode: descriptions only, no code information \\
#        & implies -l and -s \\ \hline
#   -b   & Bare mode, meaning no preamble, etc.  \\ \hline
#   -i   & internal mode: omit prologues marked !BOPI  \\ \hline
Momme Butenschoen's avatar
Momme Butenschoen committed
58
#   -g   & Use GEOS style. Implies -n unless overidden. \\ hline
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
#   +/-n & New Page for each subsection (wastes paper) \\ \hline
#   +/-l & Listing mode, default is prologues only \\ \hline
#   +/-s & Shut-up mode, i.e., ignore any code from BOC to EOC \\ \hline
#   +/-x & No LaTeX mode, i.e., put !DESCRIPTION: in verbatim mode \\ \hline
#   +/-f & No source file info \\ \hline
#   -A   & Ada code \\ \hline
#   -C   & C++ code \\ \hline
#   -F   & F90 code (default) \\ \hline
#   -S   & Shell script \\ \hline
#   none & Print help message \\ \hline \hline
# \end{tabular}
# \end{center}
#
# The options can appear in any order.  The options -g, -h and -b, affect
# the input from all files listed on command-line input.  Each of the
# remaining options affects only the input from the files listed after
# the option and prior to any overriding option.  The plus sign
# turns off the option.  For example, the command-line input,
# \bv
#      protex -bnS File1 -F File2.f +n File3.f
# \ev
# will cause the option, {\tt -n} to affect the input from the files,
# {\tt File} and {\tt File2.f}, but not from {\tt File3.f}.  The
# {\tt -S} option is implemented for {\tt File1} but is overridden by
# the {\tt -F} for files {\tt File2.f} and {\tt File3.f}.
#
#
# !SEE ALSO:
#         For a more detailed description of ProTeX functionality,
#         DAO Prologue and other conventions, consult:
#
90
#           Sawyer, W., and A. da Silva, 1997: ProTeX: A Sample
91 92
#           Fortran 90 Source Code Documentation System.
#           DAO Office Note 97-11
93
#
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
# !AUTHOR:
# !       Momme Butensch\xf6n
#
# !REVISION HISTORY:
#
#  20Dec1995  da Silva  First experimental version
#  10Nov1996  da Silva  First internal release (v1.01)
#  28Jun1997  da Silva  Modified so that !DESCRIPTION can appear after
#             !INTERFACE, and !INPUT PARAMETERS etc. changed to italics.
#  02Jul1997  Sawyer    Added shut-up mode
#  20Oct1997  Sawyer    Added support for shell scripts
#  11Mar1998  Sawyer    Added: file name, date in header, C, script support
#  05Aug1998  Sawyer    Fixed LPChang-bug-support-for-files-with-underscores
#  10Oct1998  da Silva  Introduced -f option for removing source file info
#                       from subsection, etc.  Added help (WS).
109
#  06Dec1999  C. Redder Added LaTeX command "\label{sec:prologues}" just
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
#                       after the beginning of the proglogue section.
#  13Dec1999  C. Redder Increased flexbility in command-line
#                       interface.  The options can appear in any
#                       order which will allow the user to implement
#                       options for select files.
#  01Feb1999  C. Redder Added \usepackage commands to preamble of latex
#                       document to include the packages amsmath, epsfig
#                       and hangcaption.
#  10May2000  C. Redder Revised LaTeX command "\label{sec:prologues}"
#                       to "\label{app:ProLogues}"
#  10/10/2002 da Silva  Introduced ARGUMENTS keyword, touch ups.
#
#  15Jan2003  R. Staufer  Modified table of contents to print only section headers - no descriptions
#
#  25Feb2003  R. Staufer  Added BOPI/EOPI and -i (internal) switch to provide the option of omitting prologue information from output files.
#  31Mar2014  M. Butenschoen Changed heading style to use sections for modules.
#  22Oct2014  M. Butenschoen Conversion to python with consistent changes 
#                            to use part for top-level and section for 2nd
#                            level. Introduced -d option.
129
#  22Oct2014  M. Butenschoen -h option produces human-readable
130 131 132 133 134 135
#                            documentation with desciptions only omitting
#                            any iformation on the code.
#                            Help string is now obtained by calling without#                            argument
#
#EOP
#----------------------------------------------------------------------------
Momme Butenschoen's avatar
Momme Butenschoen committed
136
#BOC
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
from __future__ import print_function
from sys import argv,stderr,stdout
from time import localtime,strftime
from re import sub
from re import split as rsplit


#----------------------------------------------------------------------

class PyProTex:

  def __init__(self,Choices):
    """Initiate class object with all options and settings.
           Choices: PyProTex options as list of input strings in."""
    
    #Option Classes
    self.GlobOptions=["h","b","g"]
    self.LangOptions=["A","C","F","S"]
    self.SwOptions=["f","l","i","n","s","x"]
    self.RegOptions=self.GlobOptions+self.LangOptions
    #Default Options
    self.opt={}
    self.opt["h"]=0
    self.opt["b"]=0
    self.opt["g"]=0
    self.opt["f"]=0
    self.opt["l"]=0
    self.opt["i"]=0
    self.opt["n"]=0
    self.opt["s"]=0
    self.opt["x"]=0
    self.opt["A"]=0
    self.opt["C"]=0
    self.opt["S"]=0
    self.opt["F"]=1 #Default file format is fortran

    # Optional Prologue Keywords
    # --------------------------
    self.keys =    [ "!INTERFACE:",
            "!USES:",
            "!PUBLIC TYPES:",
            "!PRIVATE TYPES:",
            "!PUBLIC MEMBER FUNCTIONS:",
            "!PRIVATE MEMBER FUNCTIONS:",
            "!PUBLIC DATA MEMBERS:",
            "!PARAMETERS:",
            "!ARGUMENTS:",
            "!IMPORT STATE:",
            "!EXPORT STATE:",
            "!INTERNAL STATE:",
            "!DEFINED PARAMETERS:",
            "!INPUT PARAMETERS:",
            "!INPUT/OUTPUT PARAMETERS:",
            "!OUTPUT PARAMETERS:",
            "!RETURN VALUE:",
            "!REVISION HISTORY:",
            "!BUGS:",
            "!SEE ALSO:",
            "!SYSTEM ROUTINES:",
            "!FILES USED:",
            "!REMARKS:",
            "!TO DO:",
            "!CALLING SEQUENCE:",
            "!AUTHOR:",
            "!CALLED FROM:",
            "!LOCAL VARIABLES:" ]

    # Initialize these for clarity
    # ----------------------------
    self.intro = 0             # doing introduction?
    self.prologue = 0          # doing prologue?
    self.first = 1             # first prologue?
    self.source = 0            # source code mode?
    self.verb = 0              # verbatim mode?
    self.tpage = 0             # title page?
    self.begdoc = 0            # has \begin{document} been written?
    self.descr_verb = 0        # descriptions in LaTeX mode
    self.inspec = 0            # are we processing state specs (GEOS)
    self.initem = 0            # are we processing state specs item (GEOS)
    self.skip = 0              # don't skip

    # Set for global options
    # -----------------------

    for choice in Choices:
      option = self.CheckOpts (choice,)
      if option:
        rc=self.GetOpts(choice,self.GlobOptions)
      else:
        print("Invalid option string: {}".format(choice),file=stderr)
        self.print_help(dest=stderr)

    # g option requires n option 
    # ---------------------

    if self.opt["g"]: self.opt["n"]=1

    # Set for non-global options
    # -----------------------
    for choice in Choices:
      option = self.CheckOpts(choice,quiet_mode=1)+1 
      if option:
        self.GetOpts(choice,self.SwOptions)
        self.SetLanguage(choice)

    # d option implies s option and no l option
    # ---------------------

    if self.opt["g"]:
        self.opt["s"]=1
        self.opt["l"]=0

249 250 251
    # Determine the type of code, set corresponding search strings
    # ------------------------------------------------------------
    # DEFAULT: FORTRAN
252 253 254 255 256 257 258 259 260 261 262 263
    if self.opt["A"]:            # ADA
        self.comment_string = '--'
        self.boi_string = '--BOI'
        self.eoi_string = '--EOI'
        self.bop_string = '--BOP'
        self.eop_string = '--EOP'
        self.bopi_string = '--BOPI'
        self.eopi_string = '--EOPI'
        self.boc_string = '--BOC'
        self.eoc_string = '--EOC'
        self.boe_string = '--BOE'
        self.eoe_string = '--EOE'
264
    elif self.opt["C"]: # C
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
        self.comment_string = '//'
        self.boi_string = '//BOI'
        self.eoi_string = '//EOI'
        self.bop_string = '//BOP'
        self.eop_string = '//EOP'
        self.bopi_string = '//BOPI'
        self.eopi_string = '//EOPI'
        self.boc_string = '//BOC'
        self.eoc_string = '//EOC'
        self.boe_string = '//BOE'
        self.eoe_string = '//EOE'
    elif self.opt["S"]:            # Script
        self.comment_string = '#'
        self.boi_string = '#BOI'
        self.eoi_string = '#EOI'
        self.bop_string = '#BOP'
        self.eop_string = '#EOP'
282 283
        self.bopi_string = '#BOPI'
        self.eopi_string = '#EOPI'
284 285 286 287
        self.boc_string = '#BOC'
        self.eoc_string = '#EOC'
        self.boe_string = '#BOE'
        self.eoe_string = '#EOE'
288
    else:
289 290 291 292 293 294 295 296 297 298 299 300
        self.comment_string = '!'
        self.boi_string = '!BOI'
        self.eoi_string = '!EOI'
        self.bop_string = '!BOP'
        self.eop_string = '!EOP'
        self.bopi_string = '!BOPI'
        self.eopi_string = '!EOPI'
        self.boc_string = '!BOC'
        self.eoc_string = '!EOC'
        self.boe_string = '!BOE'
        self.eoe_string = '!EOE'

301 302
    # Set date
    # --------
303
    self.Date = strftime("%a %b %d %T %Z",localtime())
304

305 306 307 308 309 310 311 312 313
    # Initial LaTeX stuff
    # -------------------
    self.Str=""
    self.Str+=self.print_notice()        # auto-generation warning
    self.Str+=self.print_preamble()      # \documentclass, text dimensions, etc.
    self.Str+=self.print_macros()        # short-hand LaTeX macros

  def __call__(self,files):
    """Process all files in argument list, line by line, 
Momme Butenschoen's avatar
Momme Butenschoen committed
314 315
    compiling the documentation Tex source into the self.Str string
    attribute.
316
            files: list of input files"""
317 318 319 320 321
    # If no file arguments are present print help string and exit
    # ---------------------

    if not files: self.print_help()
    
322
    for f in files:  
323 324
       # Set file name parameters
       # ------------------------
325 326 327
       self.InputFile           = f
       self.all_path_components = self.InputFile.split("/")
       self.FileBaseName        = self.all_path_components[-1].replace("_","\_")
328 329
       # Open current file
       # -----------------
330 331 332 333 334
       try:
          fid=open(self.InputFile,'r')
       except:
          raise RunTimeError,"Unable to open {}".format(self.InputFile)

335 336
       # Print page header
       # -----------------
337 338

       if self.opt["g"]:
339 340 341 342 343
          self.shname =  " "
          self.lnname =  " "
          self.units  =  " "
          self.dims   =  " "
          self.locs   =  " "
344
       else:
345
          self.Str+="\n\markboth{{Left}}{{Source File: {},  Date: {}}}\n\n".format(self.FileBaseName,self.Date)
346

347 348
       # Process input file line by line:
       # ---------------------------------------------------------
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378

       Lines=fid.readlines()
       for line in Lines:
          Record=line.rstrip("\n") #strip record separator
          self._processRecord(Record)

    #close document
    self.Str+="\n"
    if self.source: self.do_eoc()
    self.Str+="\n%...............................................................\n"

    # see comment above where these are originally set.
    #print "\\setlength{\\parskip}{\\oldparskip}";
    #print "\\setlength{\\parindent}{\\oldparindent}";
    #print "\\setlength{\\baselineskip}{\\oldbaselineskip}";

    if not self.opt["b"]:
      self.Str+="\n\\end{document}"

  def _processRecord(self,Rec): 
     """Process a record according to its context."""

     Fld=Rec.split(None,9999) #split line by whitespace
     if len(Fld)==0: return #skip empty lines
     if Fld[0] == "!QUOTE:" or (self.opt["g"] and len(Fld)>1 and Fld[1] == "!!GEOS!!"):
        self.Str+="\n"
        for f in Fld[1:]:
           self.Str+="{} ".format(f)
        return

379 380
     # Start the intro at new line and switch intro on
     # -------------------------------------------
381 382 383 384 385
     if Fld[0] == self.boi_string:
        self.Str+="\n"
        self.intro = 1
        return

386 387
     # If within intro and title is given print title and switch title page on
     # -------------------------------------------
388 389 390 391 392 393
     if len(Fld)>1 and Fld[1] == '!TITLE:':
        if self.intro:
           title = "{}".format(" ".join(*Fld[2]))
           self.tpage = 1
           return

394 395
     # If within intro and author is given print title and switch title page on
     # -------------------------------------------
396 397 398 399 400 401
     if len(Fld)>1 and Fld[1] == '!AUTHOR:':
        if self.intro:
           author = Fld[2]
           self.tpage = 1
           return

402
     # If within intro and affiliation is given print title and set title page
403 404 405 406 407 408 409
     #       -------------------------------------------
     if len(Fld)>1 and Fld[1] == '!AFFILIATION:':
        if self.intro:
           affiliation = "{}".format(" ".join(*Fld[2]))
           self.tpage = 1
           return

410 411
     # If within intro and date is given print date and switch title page on
     # -------------------------------------------
412 413 414 415 416 417
     if len(Fld)>1 and Fld[1] == '!DATE:':
        if self.intro:
           self.date="{}".format(" ".join(*Fld[2]))
           self.tpage = 1
           return

418 419
     # If within intro and introduction is given print introduction header and switch title page on 
     # -------------------------------------------
420 421 422 423 424 425 426 427 428 429 430
     if len(Fld)>1 and Fld[1] == '!INTRODUCTION:':
        if self.intro:
           self.self,do_beg()
           self.Str+=" \n"
           self.Str+="%..............................................\n"
           if self.opt["g"]:
             self.Str+="\part{{\Large {} }}\n".format(" ".join(*Fld[2:]))
           else:
             self.Str+="\part{{ {} }}\n".format(" ".join(*Fld[2:]))
           return

431 432
     # close introduction and switch off intro
     # -------------------
433 434 435 436 437 438 439 440

     if Fld[0] == self.eoi_string:
           self.Str+=" \n"
           self.Str+="%/////////////////////////////////////////////////////////////\n"
           self.Str+="\\newpage\n"
           self.intro = 0
           return

441 442 443 444
     # Beginning of prologue : print header and
     # switch on prologue
     # switch off verb, source and inspec
     # ---------------------
445
     if Fld[0] == self.bop_string:
Momme Butenschoen's avatar
Momme Butenschoen committed
446
        self.skip=0
447 448 449 450 451 452
        if self.source: self.do_eoc()
        self.Str+=" \n"
        self.Str+="%/////////////////////////////////////////////////////////////\n"
        self.do_beg()
        if self.first or self.opt["n"]:
           if not (self.opt["b"] or self.opt["g"]):
453
              self.Str+="\part{Routine/Function Prologues} \label{app:ProLogues}\n"
454 455 456 457 458 459 460 461 462 463 464 465
        else:
           self.Str+=" \n"
           self.Str+="\mbox{}\hrulefill\\ \n"
           self.Str+=" \n"
        self.first = 0
        self.prologue = 1
        self.verb = 0
        self.source = 0
        self.inspec = 0
        self.set_missing()   # initialise keyword check
        return

466 467
     # Beginning of internal prologue (switchable)
     # ------------------------------
468 469 470 471 472 473 474 475 476
     if Fld[0] == self.bopi_string:
        if self.opt["i"]:
           self.prologue = 0 #No internal prologue with i option
        else:
           if self.source: self.do_eoc() #if source is still active close it and close verbatim
           self.Str+=" \n"
           self.Str+="%/////////////////////////////////////////////////////////////\n"
           self.do_beg()
           if self.first or self.opt["n"]:
477
              if not (self.opt["b"] or self.opt["g"]):
478 479 480 481 482 483 484 485 486 487 488 489 490
                 self.Str+="\part{Routine/Function Prologues} \label{{app:ProLogues}}\n"
           else:
              self.Str+=" \n"
              self.Str+="\mbox{}\hrulefill\\\ \n"
              self.Str+=" \n"
           self.first = 0
           self.prologue = 1
           self.verb = 0
           self.source = 0
           self.inspec = 0
           self.set_missing()    # initialise keyword check
           return

491 492
     # A new subroutine/function
     # -------------------------
493 494 495 496 497 498
     if len(Fld)>1 and Fld[1] == '!ROUTINE:':
        if self.prologue:
           self.name_is = " ".join(Fld[2:])
           name=self.name_is.replace("_","\_")# Replace "_" with "\_"
           if self.opt["n"] and not self.first: self.Str+="\n\\newpage\n"
           if self.opt["f"]:
499
              self.Str+="\n\\section{{{} }}\n\n".format(name)
500
           else:
501
              self.Str+="\n\section{{{} (Source: {})}}\n\n".format(name, self.FileBaseName)
502 503 504 505
           self.have_name = 1
           self.first = 0
           return

506 507
     # A new Module
     # ------------
508 509 510 511 512 513 514 515 516 517
     if len(Fld)>1 and Fld[1] == '!MODULE:':
        if self.prologue:
           self.name_is = " ".join(Fld[2:])
           name=self.name_is.replace("_","\_")# Replace "_" with "\_"
           if self.opt["n"] and not self.first: self.Str+="\n\\newpage\n"
           if self.opt["g"]:
              self.Str+="\n\section [{0}] {{Module {0} }}\n\n".format(name)
           else:
              if self.opt["f"]:
                 self.Str+="\n\section{{Module: {} }}\n\n".format(name)
518
              else:
519 520 521 522 523 524
                 self.Str+="\n\section{{Module: {} (Source: {})}}\n\n".format(name,self.FileBaseName)
           self.have_name = 1
           self.have_intf = 1  # fake, does not need one.
           self.first = 0
           return

525 526
     # A new include file
     # ------------------
527 528 529 530 531
     if len(Fld)>1 and Fld[1] == '!INCLUDE:':
        if self.prologue:
           self.name_is = " ".join(Fld[2:])
           name=self.name_is.replace("_","\_")# Replace "_" with "\_"
           if self.opt["n"] and not self.first: self.Str+="\n\\newpage\n"
532
           if self.opt["f"]:
533 534 535 536 537 538 539 540
              self.Str+="\n\subsection{{Include File {} }}\n\n".format(name)
           else:
              self.Str+="\n\subsection{{Include File {} (Source: {})}}\n\n".format(name,self.FileBaseName)
           self.have_name = 1
           self.have_intf = 1  # fake, does not need one.
           self.first = 0
           return

541 542
     # A new INTERNAL subroutine/function
     # ----------------------------------
543 544 545 546 547 548 549 550 551 552 553 554 555
     if len(Fld)>1 and Fld[1] == '!IROUTINE:':
        if self.prologue:
           self.name_is = " ".join(Fld[2:])
           name=self.name_is.replace("_","\_")# Replace "_" with "\_"
           words = name.split()
           if self.opt["n"] and not self.first: self.Str+="\n\\newpage\n"
           if self.opt["g"]:
              self.Str+="\n\subsection {{{}}}\n\n".format(name)
           else:
              self.Str+="\n\subsection {{{}}}\n\n".format(name)
           self.have_name = 1
           return

556 557
     # A new CONTAINED subroutine/function
     # ----------------------------------
558 559 560 561
     if len(Fld)>1 and Fld[1] == '!CROUTINE:':          # Contained routine
        if self.prologue:
           self.name_is = " ".join(Fld[2:])
           name=self.name_is.replace("_","\_")# Replace "_" with "\_"
562
           words = name.split()
563 564 565 566
           self.Str+="\n\subsection{{{}}}\n\n".format(name)
           self.have_name = 1
           return

567 568
     # A new CLASS
     # ------------
569 570 571 572 573 574 575 576 577 578 579 580 581 582
     if len(Fld)>1 and Fld[1] == '!CLASS:':
        if self.prologue:
           self.name_is = " ".join(Fld[2:])
           name=self.name_is.replace("_","\_")# Replace "_" with "\_"
           if self.opt["n"] and not first: self.Str+="\n\\newpage\n"
           if self.opt["f"]:
              self.Str+="\n\section{{C++:  Class Interface {} }}\n\n".format( self.name_is)
           else:
              self.Str+="\n\section{{C++:  Class Interface {} (Source: {})}}\n\n".format(self.name_is,self.FileBaseName)
           self.have_name = 1
           self.have_intf = 1  # fake, does not need one.
           self.first = 0
           return

583 584
     # A new Method
     # -------------------------
585 586 587 588 589 590 591 592 593 594 595 596 597 598
     if len(Fld)>1 and Fld[1] == '!METHOD:':
        if self.prologue:
           self.name_is = " ".join(Fld[2:])
           name=self.name_is.replace("_","\_")# Replace "_" with "\_"
           if self.opt["n"] and not self.first:
              self.Str+="\n\\newpage\n"
           if self.opt["f"]: 
              self.Str+="\n\subsection{{{}}}\n\n".format(name)
           else:
              self.Str+="\n\subsection{{{} (Source: {})}}\n\n".format(name,self.FileBaseName)
           self.have_name = 1
           self.first = 0
           return

599 600
     # A new function
     # -------------------------
601 602 603 604 605 606 607 608 609 610 611 612 613
     if len(Fld)>1 and Fld[1] == '!FUNCTION:':
        if self.prologue:
           self.name_is = " ".join(Fld[2:])
           name=self.name_is.replace("_","\_")# Replace "_" with "\_"
           if self.opt["n"] and not self.first: self.Str+="\n\\newpage\n"
           if self.opt["f"]:
              self.Str+="\n\subsection{{{}}}\n\n".format(names)
           else:
              self.Str+="\n\subsection{{{}(Source: {})}}\n\n".format(name,self.FileBaseName)
           self.have_name = 1
           self.first = 0
           return

614 615
     # Description: what follows will be regular LaTeX (no verbatim)
     # -------------------------------------------------------------
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
     if "!DESCRIPTION:" in Rec:
        if self.prologue:
           self.skip=0 
           # if still active close verbatim and switch off 
           if self.verb:
              self.Str+="\n\end{verbatim}"
              self.Str+="\n{{\sf \\bf DESCRIPTION:\\\ }}\n\n"
              self.verb = 0
           if self.opt["x"]: #description not latex
              self.Str+="\n\\begin{verbatim} "
              self.verb = 1
              self.descr_verb = 1
           else:
              for f in Fld[2:]:
                 self.Str+="\n{} ".format(f)
           # self.Str+=" "
           self.have_desc = 1
           return

635 636
     # Handle optional keywords (these will appear as verbatim)
     # --------------------------------------------------------
637 638 639
     if self.prologue:
        for key in self.keys:
           if key in Rec:
640
             if self.opt['h']:  
641 642 643 644 645 646 647 648 649 650 651 652
                self.skip=1
                return
             else:
               if self.verb: #switch off verbatim to create heading
                 self.Str+="\n\end{verbatim}\n"
                 self.verb = 0
               k = "{}".format(key)
               ln = len(k)
               Rec=key
               if self.opt["g"]:
                 if ("/IMPORT STATE/" in key) or ("/EXPORT STATE/" in key) or ("/INTERNAL STATE/" in key):
                    if self.inspec:
653
                       self.beg_item()
654
                    self.Str+="\n \\bigskip \n {{\\bf  {} }} \n\n".format(k[1:ln])
655 656 657 658
                    self.hed_item()
                    self.inspec = 1
                    self.initem = 0
                    return
659
                 else:
660
                    self.Str+="\n{{\\bf {}}}".format(k[1:ln]) # italics
661 662
               else:
                 if ("/USES/" in key) or ("/INPUT/" in key) or ("/OUTPUT/" in key) or ("/PARAMETERS/" in key) or ("/VALUE/" in key) or  ("/ARGUMENTS/" in key):
663
                    self.Str+="\n{{\em {}}}".format(k[1:ln]) # italics
664
                 else:
665
                    self.Str+="\n{{\\sf {}}}".format(k[1:ln]) # san serif
666 667 668 669 670 671 672 673 674
               #switch verbatim back on:      
               self.Str+="\n\\begin{verbatim}"
               self.verb = 1
               self.descr_verb = 1
               if key == "!INTERFACE:":         self.have_intf = 1
               if key == "!CALLING SEQUENCE:":  self.have_intf = 1
               if key == "!REVISION HISTORY:":  self.have_hist = 1
               return

675 676
     # End of prologue
     # ---------------
677 678 679 680 681
     if Fld[0] == self.eop_string:
        if self.verb: #close and switch off verbatim
           self.Str+="\n\end{verbatim}\n"
           self.verb = 0
        if self.opt["g"] and self.inspec:
682
           self.beg_item()
683 684 685 686 687 688 689 690 691
           self.inspec = 0
        self.prologue = 0 #switch off prologue
        if self.opt["l"]:
           Fld[0] = self.boc_string
        else:
           return

     if not self.opt["s"]:

692 693
        # End of Internal Prologue
        # ------------------------
694 695 696 697 698
        if Fld[0] == self.eopi_string:
           if self.verb: #close and switch off verbatim
              self.Str+="\n\end{verbatim}\n"
              self.verb = 0
           if self.opt["g"] and self.inspec:
699
              self.beg_item()
700 701 702 703 704 705 706 707
              self.inspec = 0
           self.prologue = 0
           if self.opt["l"]:
              Fld[0] = self.boc_string
           else:
              return

        #
708 709
        # Beginning of source code section
        # --------------------------------
710 711 712 713 714 715 716 717 718 719
        if Fld[0] == self.boc_string:
           self.Str+=" \n"
           self.Str+="%/////////////////////////////////////////////////////////////\n"
           self.first = 0
           self.prologue = 0
           self.source = 1
           self.Str+="\n\\begin{verbatim}"
           self.verb = 1
           return

720 721
        # End of source code
        # ------------------
722 723
        if Fld[0] == self.eoc_string:
           self.do_eoc() #if source is still active close it and close verbatim
724

725 726 727
           self.prologue = 0
           return

728 729
        # Beginning of example prologue
        # (separated in latex source but not in output)
730 731 732 733 734 735 736 737 738 739 740
        #          -----------------------------
        if Fld[0] == self.boe_string:
           if self.source: self.do_eoc() #if source is still active close it and close verbatim
           self.Str+=" \n"
           self.Str+="%/////////////////////////////////////////////////////////////\n"
           self.first = 0
           self.prologue = 1
           self.verb = 0
           self.source = 0
           return

741 742
        # End of example prologue
        # -----------------------
743 744 745 746 747 748 749 750 751 752
        if Fld[0] == self.eoe_string:
           if self.verb:
              self.Str+="\n\end{verbatim}\n"
              self.verb = 0
           self.prologue = 0
           if self.opt["l"]:
              Fld[0] = self.boc_string
           else:
              return

753 754
     # Prologue or Introduction, print regular line (except for !)
     # -----------------------------------------------------------
Momme Butenschoen's avatar
Momme Butenschoen committed
755
     if not self.skip and (self.prologue or self.intro):
756 757 758 759
        if self.verb and len(Fld)==1 and Fld[0]==self.comment_string: 
           return
        elif(self.opt["g"]):
           if self.verb and len(Fld)==2 and Fld[0]=='implicit':
760
              return
761
           elif self.verb and len(Fld)==1 and Fld[0] == 'private':
762
              return
763 764 765 766 767
        elif len(Fld)>1 and Fld[1] == "\\ev":  # special handling
           Rec = self.comment_string+" \end{verbatim}"
        Rec=Rec.replace(self.comment_string," ")       # replace comment string with blank
        if self.opt["g"] and self.inspec:
           if Fld[0] == "call":
768
              self.beg_item()
769 770 771 772
              return
           elif len(Fld)>1 and Fld[1] == "=":
              self.prc_item(Fld)
        else:
773
           self.Str+="\n{}".format(Rec)
774 775
        self.descr_verb = 0

776 777
     # Source code: print the full line
     # --------------------------------
778 779 780 781 782 783 784 785 786 787
     if self.source and not self.skip:
        self.Str+="\n"+Rec
        return

  def __str__(self,):
      return self.Str

  def CheckOpts(self,optStr,quiet_mode=0):
      """Checks options against a given list.  Outputs error message
       for any invalid option.
788

789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
          string: optStr - options to be checked. (e.g. -df+x)  The
                               string must begin with a positive or
                               negative sign.  If no sign appears at the
                               beginning or by itself, then the argument
                               is not recognized as a list of options.
          string: valid_reg_options - string of valid regular options.
                               (i.e. options that are associated only
                               eith negative sign.)
          string: valid_sw_options - string of valid switch options.
                               (i.e. options that can be associated with
                               either a positive or negative sign.
          logical:   quiet mode (optional) If True then print no error
                               messages.
       Returns:         integer return code
                               = 0 if the arguement, options, is
                                  not recognized as a list of options
                               =  1 if all options are valid.
                               >  1 for the number of invalid options.
807
      """
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841

      if ( optStr=="+" or optStr=="-" ): return -1
      Options = [c for c in optStr] #split up string in single characters
      if Options[0]!="-" and Options[0]!="+": return -1
      flag = 1
      for option in Options:
        if option == "-" or option == "+": 
           option_sign = option
        else:
           if option_sign == "-":
              valid_options = self.RegOptions+self.SwOptions
           else:
              valid_options = self.SwOptions
           if option not in valid_options and quiet_mode:
              flag+=1
              print("Invalid option: {}{}\n".format(option_sign,option),file=stderr) 
              self.print_help(dest=stderr)
      return flag

  def GetOpts(self,optStr,valid_options):
      """Gets options.  If an option is valid, then self.opt[option] is
      set to 0 or 1 in relation to if the option is preceeded 
      by a positive or negative sign.
 
        string: optStr - options to be checked. (e.g. -df+x)  The
                             list must begin with a positive or
                             negative sign.  If no sign appears at the
                             beginning or by itself, then the argument
                             is not recognized as a list of options.
        string: valid_options - list of valid options (e.g. dfhx)
      Returns:         integer return code
                             = -1 if the arguement, options, is
                                not recognized as a list of options.
                             =  0 otherwise
842
      """
843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858

      if optStr == "+" or optStr == "-": return -1
      Options = [c for c in optStr] #split up string in single characters
      if Options[0]!="-" and Options[0]!="+": return -1
      for option in Options:
        if option == "-" or option == "+": 
           option_sign = option
        else:
           if option in valid_options:
             if option_sign == "-":
               self.opt[option] = 1
             elif option_sign == "+":
               self.opt[option] = 0
      return 0

  def SetLanguage(self,optStr):
859 860 861
      """Sets the language option.
      The last input option that is a LanguageOption will overrule
      all others,  i.e. for all other language options in the list,
862
      opt_[option] is set to 0. Other options are ignored.
863

864 865 866 867 868 869 870 871 872
        string: optStr - options to be checked. (e.g. -df+x)  The
                             list must begin with a positive or
                             negative sign.  If no sign appears at the
                             beginning or by itself, then the argument
                             is not recognized as a list of options.
      Returns:           integer return code
                             = -1 if the arguement, options, is
                                not recognized as a list of options.
                             =  0 otherwise
873
      """
874 875 876 877 878 879 880 881 882 883 884 885 886 887

      if optStr == "+" or optStr == "-": return -1
      Options = [c for c in optStr] #split up string in single characters
      ValidOptions = [c for c in self.LangOptions] #split up string in single characters
      for option in Options:
        if option != "-" and option != "+": 
           if option in self.LangOptions:
              for valid_option in self.LangOptions:
                 self.opt[valid_option]=0
              self.opt[option]=1
      return 0

  def print_help(self,dest=stdout):
      """Print help string, by default to standard output."""
888
      print("Usage:     PyProTex.py [-hbACFS] [+-nlsxf] src_file[s]",file=dest)
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906
      print(" ",file=dest)
      print(" Options:",file=dest)
      print("     -h   Human mode: descriptions only, no code information",file=dest)
      print("                      implies -l and -s",file=dest)
      print("     -b   Bare mode, meaning no preamble, etc.",file=dest)
      print("     -d   descriptions only, implies +s and -l",file=dest)
      print("     +-n  New Page for each subsection (wastes paper)",file=dest)
      print("     +-l  Listing mode, default is prologues only",file=dest)
      print("     +-i  drop internal prologues",file=dest)
      print("     +-s  Shut-up mode, i.e., ignore any code from BOC to EOC",file=dest)
      print("     +-x  No LaTeX mode, i.e., put !DESCRIPTION: in verbatim mode",file=dest)
      print("     +-f  No source file info",file=dest)
      print("     -A   Ada code",file=dest)
      print("     -C   C++ code",file=dest)
      print("     -F   F90 code",file=dest)
      print("     -S   Shell script",file=dest)
      print(" ",file=dest)
      print("  The options can appear in any order.  The options, -h and -b,",file=dest)
907 908 909 910
      print("  affect the input from all files listed on command-line input.",file=dest)
      print("  Each of the remaining options effects only the input from the",file=dest)
      print("  files listed after the option and prior to any overriding",file=dest)
      print("  option.  The plus sign turns off the option.",file=dest)
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
      raise SystemExit()

  def print_notice(self,):
      """Add auto generation disclaimer to output string."""
      Str="%                **** IMPORTANT NOTICE *****" 
      Str+="% This LaTeX file has been automatically produced by PyProTex"
      Str+="% Any changes made to this file will likely be lost next time"
      Str+="% this file is regenerated from its source."
      Str+=" "
      return Str

  def print_preamble(self,):
      """Add Latex Preamble to output string."""
      Str=""
      if not self.opt["b"]:
        Str+="%------------------------ PREAMBLE --------------------------\n"
        Str+="\\documentclass[11pt]{article}\n"
        Str+="\\usepackage{amsmath,amsfonts,mathrsfs}\n"
        Str+="\\usepackage{epsfig}\n"
        Str+="\\usepackage{hangcaption}\n"
        Str+="\\textheight     9in\n"
        Str+="\\topmargin      0pt\n"
        Str+="\\headsep        1cm\n"
        Str+="\\headheight     0pt\n"
        Str+="\\textwidth      6in\n"
        Str+="\\oddsidemargin  0in\n"
        Str+="\\evensidemargin 0in\n"
        Str+="\\marginparpush  0pt\n"
        Str+="\\pagestyle{myheadings}\n"
        Str+="\\markboth{}{}\n"
        Str+="%-------------------------------------------------------------\n"

943 944
        # in your main document before you include any protex-generated files
        # for the first time, if you define these three variables as length
945 946 947 948 949
        # settings (like this:)
        #   \newlength{\oldparskip}
        #   \newlength{\oldparindent}
        #   \newlength{\oldbaselineskip}
        # then 1) comment in all the lines below, and 2) find the 3 reset lines
950 951 952
        # further down and comment in them as well.
        # then protex will override the paragraph and skip settings during
        # the source sections, but will restore the original document settings
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994
        # at the end.   if someone can figure out how to check to see if a
        # latex variable exists, and do a conditional section, we could make
        # this fully self-contained.
        # nsc feb 2003

        #.Str+="\\setlength{\\oldparskip}{\\parskip}\n"
        Str+="\\setlength{\\parskip}{0pt}\n"
        #Str+="\\setlength{\\oldparindent}{\\parindent}\n"
        Str+="\\setlength{\\parindent}{0pt}\n"
        #Str+="\\setlength{\\oldbaselineskip}{\\baselineskip}\n"
        Str+="\\setlength{\\baselineskip}{11pt}\n"
      return Str

  def print_macros(self,):
     """Add macro definitions to output string."""
     Str=" \n"
     Str+="%--------------------- SHORT-HAND MACROS ----------------------\n"
     Str+="\\def\\bv{\\begin{verbatim}}\n"
     Str+="\\def\\ev{\\end{verbatim}}\n"
     Str+="\\def\\be{\\begin{equation}}\n"
     Str+="\\def\\ee{\\end{equation}}\n"
     Str+="\\def\\bea{\\begin{eqnarray}}\n"
     Str+="\\def\\eea{\\end{eqnarray}}\n"
     Str+="\\def\\bi{\\begin{itemize}}\n"
     Str+="\\def\\ei{\\end{itemize}}\n"
     Str+="\\def\\bn{\\begin{enumerate}}\n"
     Str+="\\def\\en{\\end{enumerate}}\n"
     Str+="\\def\\bd{\\begin{description}}\n"
     Str+="\\def\\ed{\\end{description}}\n"
     Str+="\\def\\({\\left (}\n"
     Str+="\\def\\){\\right )}\n"
     Str+="\\def\\[{\\left [}\n"
     Str+="\\def\\]{\\right ]}\n"
     Str+="\\def\\<{\\left  \\langle}\n"
     Str+="\\def\\>{\\right \\rangle}\n"
     Str+="\\def\\cI{{\\cal I}}\n"
     Str+="\\def\\diag{\\mathop{\\rm diag}}\n"
     Str+="\\def\\tr{\\mathop{\\rm tr}}\n"
     Str+="%-------------------------------------------------------------\n"
     return Str

  def do_beg(self,):
995
     """Add title page to output string."""
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
     if not self.opt["b"]:
       if self.begdoc == 0:
         if self.tpage:
            self.Str+="\n\\title{@title}\n"
            self.Str+="\\author{\\sc {}}\\\\ {\\em {}}}\n".format(self.author,self.affiliation)
            self.Str+="\\date{{{}}}\n".format(self.date)
         self.Str+="\\begin{document}\n"
         if self.tpage:
            self.Str+="\\maketitle\n"
         self.Str+="\\tableofcontents\n"
         self.Str+="\\newpage\n"
         self.begdoc = 1

  def do_eoc(self,):
      """At eoc close verbatim and set source to false."""
      self.Str+="\n"
      if self.verb:
         self.Str+="\end{verbatim}"
         self.verb = 0
      self.source = 0

  def set_missing(self,):
      """Reset section attributes for later checking."""
      self.have_name = 0;      # have routine name?
      self.have_desc = 0;      # have description?
      self.have_intf = 0;      # have interface?
      self.have_hist = 0;      # have revision history?
      self.name_is = "UNKNOWN";
1024

1025 1026 1027 1028 1029 1030 1031 1032 1033
  def check_if_all_there(self,):
       """Checking for section attributes."""
       self.check_error(self.have_name,"!(I)ROUTINE:")
       self.check_error(self.have_desc,"!DESCRIPTION:")
       self.check_error(self.have_intf,"!INTERFACE:")
       self.check_error(self.have_hist,"!REVISION HISTORY:")

  def check_error(self,flag,tag):
      """Raise prologue status error flag is False."""
1034
      if not flag:
1035 1036 1037
         raise RunTimeError,"ProTeX: invalid prologue, missing {}: in {}".format(tag,self.name_is)

  def hed_item(self,):
1038 1039 1040 1041 1042 1043 1044
      self.Str+="\\bigskip\n{{ \\bf \sf \n"
      self.Str+="\makebox[.9 in][l]{{Short Name }} \n"
      self.Str+="\makebox[.9 in][l]{{Units      }} \n"
      self.Str+="\makebox[.7 in][l]{{Dims       }} \n"
      self.Str+="\makebox[.7 in][l]{{Vert Loc   }} \n"
      self.Str+="\makebox[4. in][l]{{Long Name  }} \n"
      self.Str+="}} \n \n"
1045 1046 1047 1048 1049 1050

  def beg_item(self,):
      if self.initem:
         if self.intv:
            self.Str+="\makebox[1.05 in][l]{{\$\overline{{\\rm \\bf {} }}\$}} \n".format(self.shname)
         else:
1051 1052
            self.Str+="\makebox[1.05 in][l]{{\\bf            {} }} \n".format(self.shname)
            self.Str+="\makebox[.9 in][l]{{ {} }} \n".format(units)
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
         if self.dims != " ":
            if self.dims != 'GEOS\_DIMSHORZONLY': 
               self.Str+="\makebox[.7 in][l]{{HorzOnly}}\n"
            elif self.dims == 'GEOS\_DIMSHORZVERT': 
               self.Str+="\makebox[.7 in][l]{{HorzVert}}\n"
            elif self.dims == 'GEOS\_DIMSVERTONLY': 
               self.Str+="\makebox[.7 in][l]{{VertOnly}}\n"
            elif self.dims == 'GEOS\_DIMSTILEONLY': 
               self.Str+="\makebox[.7 in][l]{{TileOnly}}\n"
            elif self.dims == 'GEOS\_DIMSTILETILE': 
               self.Str+="\makebox[.7 in][l]{{TileTile}}\n"
         if self.locs != " ":
            if(self.locs == 'GEOS\_VLOCATIONCENTER'):
                self.Str+="\makebox[.7 in][l]{{Center}}\n"
            elif(self.locs == 'GEOS\_VLOCATIONEDGE'):
                self.Str+="\makebox[.7 in][l]{{Edge  }}\n"
            elif(self.locs == 'GEOS\_VLOCATIONNONE'):
                self.Str+="\makebox[.7 in][l]{{None  }}\n"
         self.Str+="\makebox[4 in][l]{{\\small {} }}\\newline\n".format(self.lnname)
      self.initem=1
      self.dims=' '
      self.locs=' '
      self.intv=0

  def prc_units(self,Str):
      #outStr=Str.replace("+1","").replace(
      #s/\+1//g;
      #s/([a-zA-Z])\+([1-9][0-9]*)/{\1}\$^{\2}\$/g;
      #s/\-([1-9][0-9]*)/\$^{-\1}\$/g;
      pass

  def prc_item(self,fld):
      # Attribute name is the first field
      self.name = fld[0].upper()
      # Attribute value begins at the third field
      value=fld
      valStr = " ".join(value[2:])
      # Clean the value
      valStr=valStr.replace("_","\_").replace("\'","").replace("\"","").replace(",","").replace("&","")
      if self.name == "UNITS":
         self.prc_units()
      else:
         valStr=valStr.replace(" ","")
         if self.name == "SHORT_NAME":
            self.shname =  valStr
         elif self.name == "LONG_NAME":
            self.lnname =  valStr
         elif self.name == "UNITS":
            self.units  =  valStr
         elif self.name == "DIMS":
            self.dims   =  valStr.upper()
         elif self.name == "VLOCATION":
            self.locs   =  valStr.upper()
         elif self.name == "AVERAGING_INTERVAL":
            self.intv = 1
1108

1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
if __name__=="__main__":
    files=[]
    opts=[]
    for arg in argv[1:]:
        if arg[0] not in ("+","-",):
            files.append(arg)
        else:
            opts.append(arg)
    PPTex=PyProTex(opts) #set-up with all options
    PPTex(files) #translate all files
    print(PPTex)
Momme Butenschoen's avatar
Momme Butenschoen committed
1120
#EOC