code: def extract_context(tex_file, extracted_image_data):
      
      if os.path.isdir(tex_file) or not os.path.exists(tex_file):
          return []
  
      lines = "".join(get_lines_from_file(tex_file))
  
      # Generate context for each image and its assoc. labels
      for data in extracted_image_data:
          context_list = []
  
          # Generate a list of index tuples for all matches
          indicies = [match.span()
                      for match in re.finditer(r"(\\(?:fig|ref)\{%s\})" %
                                               (re.escape(data['label']),),
                                               lines)]
          for startindex, endindex in indicies:
              # Retrive all lines before label until beginning of file
              i = startindex - CFG_PLOTEXTRACTOR_CONTEXT_EXTRACT_LIMIT
              if i < 0:
                  text_before = lines[:startindex]
              else:
                  text_before = lines[i:startindex]
              context_before = get_context(text_before, backwards=True)
  
              # Retrive all lines from label until end of file and get context
              i = endindex + CFG_PLOTEXTRACTOR_CONTEXT_EXTRACT_LIMIT
              text_after = lines[endindex:i]
              context_after = get_context(text_after)
              context_list.append(
                  context_before + ' \\ref{' + data['label'] + '} ' +
                  context_after
              )
          data['contexts'] = context_list
docs: Extract context.
  
      Given a .tex file and a label name, this function will extract the text
      before and after for all the references made to this label in the text.
      The number of characters to extract before and after is configurable.
  
      :param tex_file (list): path to .tex file
      :param extracted_image_data ([(string, string, list), ...]):
          a list of tuples of images matched to labels and captions from
          this document.
  
      :return extracted_image_data ([(string, string, list, list),
          (string, string, list, list),...)]: the same list, but now containing
          extracted contexts