```{r}
stop("As of apaquarto version 3.0.0, the 'include' line below the metadata is no longer used and must be deleted. Right below your yaml metadata, delete this line:\n\n`{{< include _extensions/wjschne/apaquarto/_apa_title.qmd >}}`\n\nAlso, replace all non-standard prefixes like apafg- and apatb- with the standard Quarto prefixes (i.e., fig- and tbl-). Also change references to tables and figures to standard Quarto syntax. For example, `{apafg-myplot}` should now be `@fig-myplot`.")
```



```{r}
#| include: false
#| label: apasetup
# options(tidyverse.quiet = TRUE)
# library(conflicted)
# library(tidyverse)
# library(flextable)
# library(ftExtra)
# library(officer)
# library(knitr)
# 
# conflicts_prefer(dplyr::filter, .quiet = TRUE)
# conflicts_prefer(flextable::separate_header, .quiet = TRUE)
# 
# is_docx <- knitr::pandoc_to("docx", exact = FALSE)
# is_pdf <- knitr::is_latex_output()
# 
# get_metadata <- function(filename = "template.qmd") {
#   if (interactive()) {
#   rmarkdown::yaml_front_matter(filename)
#   } else {
#   rmarkdown::metadata
#   }
# }
# 
# journalmode <- get_metadata()$format$`apaquarto-pdf`$documentmode
# 
# if (is.null(journalmode)) {
#   isjournalmode <- FALSE
#   knitr::opts_chunk$set(twocolumnmode = FALSE)
# } else {
#   isjournalmode <- journalmode == "jou"
#   if (isjournalmode) {
#     knitr::opts_chunk$set(twocolumnmode = TRUE)
#   } else {
#     knitr::opts_chunk$set(twocolumnmode = FALSE)
#   }
# }
#   
# 
# if (is_pdf) {
#   library(openssl, quietly = TRUE)
#   
#   
# 
#   
#   knit_hooks$set(plot = function(x, options) {
#     if (!is.null(options$`out.width`)) {
#       figwidth <- options$`out.width`
#     } else {
#       if (!is.null(options$`fig.width`)) {
#         figwidth <- paste(options$`fig.width`, "in")
#       } else {
#         figwidth <- "\\columnwidth"
#       }
#       
#     }
# 
#     knitr::opts_current$lock(FALSE)
#     knitr::opts_current$set(output = "asis", fig.env = NULL)
#     knitr::opts_current$lock(TRUE)
# 
#     
#     filename <- paste0(opts_knit$get("base.url"), paste(x, collapse = "."))
#     
#     if (stringr::str_ends(filename, ".svg")) {
#       newname <- stringr::str_replace(filename, "svg$", "pdf")
#       if (Sys.which("rsvg-convert") == "") stop("cannot find rsvg-convert")
#       convertcommand <- paste0('rsvg-convert --format=pdf "', filename, '" > "', newname,'"')
#       shell(convertcommand)
#       filename <- newname
#       
#     }
# 
#     if (is.null(options$`apa-note`)) {
#       fignote <- NULL
#     } else {
#       fignote <-  paste0("\n\n\\figurenote{\n\\QuartoMarkdownBase64{", openssl::base64_encode(options$`apa-note`), "}\n}\n\n")
#     }
#     
#     figure_enviornment <- "figure"
#     if (!is.null(options$`apa-twocolumn`)) {
#       figure_enviornment <- ifelse(options$`apa-twocolumn` == TRUE, "figure*", "figure")
#     }
# 
# 
#     output <- paste0("\n\n\\begin{", figure_enviornment, "}[h!]\n",
#                    "\\caption{\\QuartoMarkdownBase64{", openssl::base64_encode(options$`apa-cap`), "}}\n",
#                    "\\label{", options$label, "}\n",
#       "\\includegraphics[width=",figwidth,"]{",
#       filename,
#       "}\n",
#       fignote,
#       "\n\\end{", figure_enviornment, "}\n\n"
#       )
#     # message(output)
#     output
#     })
# }
# 
# 
# knitr::knit_hooks$set(
#   `apa-figtab` = function(before, options) {
#     # Check if APA Figure or APA Table
#     if (str_starts(options$label, pattern = "apafg-") |
#         str_starts(options$label, pattern = "apatb-")) {
#       # Figure or Table
#       apatype <- ifelse(str_starts(as.character(options$label)[1],
#                                    pattern = "apafg-"),
#                         "figure",
#                         "table")
#       
#       temp_label <- knitr::opts_current$get("label")
# 
# 
#       # Format Before Chunk
#       if (before) {
#         knitr::opts_current$lock(FALSE)
#         knitr::opts_current$set(label = NULL, output = "asis")
#         knitr::opts_current$lock(TRUE)
#         options$output <- "asis"
#         if (is_pdf) {
#           
#           table_environment <- "table"
#     if (!is.null(options$`apa-twocolumn`)) {
#       table_environment <- ifelse(options$`apa-twocolumn` == TRUE, "table*", "table")
#     }
#           
#           pre <- ""
# 
#           if (apatype == "table") {
#             
#             
#             
#             pre <- paste0(pre, "```{=latex}\n\\begin{", 
#                           table_environment, 
#                           "}\n\\caption{\\QuartoMarkdownBase64{", 
#                           openssl::base64_encode(options$`apa-cap`),
#                           "}}\n\\label{",
#                           options$`label`,"}\n","```\n")
#           }
#           
#         } else {
#           pre <-
#             paste0(
#               '\n\n:::{#',
#               options$label,
#               ' .FigureTitle}\n\n{',
#               options$label,
#               '}\n\n:::\n\n'
#             )
#           
#           if (!is.null(options$`apa-cap`)) {
#             pre <- paste0(pre,
#                           '\n\n:::{.Caption}\n\n',
#                           options$`apa-cap`,
#                           '\n\n:::\n\n')
#           } else
#             stop(
#               paste0(
#                 "Chunk ",
#                 options$label,
#                 "is an APA figure/table chunk,  requires a caption. Set the `apa-cap` chunk option like so\n#| apa-cap: My caption"
#               )
#             )
#           if (!all(is.null(options$`apa-note`))) {
#             pre <- paste0(pre, '\n\n:::{.FigureWithNote}\n\n')
#             
#           } else {
#             pre <- paste0(pre, '\n\n:::{.FigureWithoutNote}\n\n')
#           }
#           
#           
#         }
#         
#         pre
#       } else {
#         # post begins here ----
#         knitr::opts_current$lock(FALSE)
#         knitr::opts_current$set(label = temp_label)
#         knitr::opts_current$lock(TRUE)
#         post <- "\n\n"
#         
#         if (is_pdf) {
#           table_environment <- "table"
#     if (!is.null(options$`apa-twocolumn`)) {
#       table_environment <- ifelse(options$`apa-twocolumn` == TRUE, "table*", "table")
#     }
#           if (apatype == "table") {
#             
#             if (!all(is.null(options$`apa-note`))) {
#               
#               columnmodepost <- ifelse(options$twocolumnmode | isjournalmode,
#                                        "\\vspace{.5em}",
#                                        "")
#               
#               post <- paste0(post, 
#                              columnmodepost,
#                              "\\tablenote{\\QuartoMarkdownBase64{", 
#                              openssl::base64_encode(options$`apa-note`), 
#                              "}}\n\n")
#             }
#             
# 
#             post <- paste0("```{=latex}\n", post, "\\end{", table_environment, "}\n```\n")
#           }
#         } else {
#           if (!all(is.null(options$`apa-note`))) {
#             post <- paste(
#               post,
#               '\n\n:::{.FigureNote custom-style="FigureNote"}\n*Note*. ',
#               options$`apa-note`,
#               '\n:::\n'
#             )
#           } else if (is_docx) {
#             post <- paste0(post,
#                            '\n\n:::{custom-style="Compact"}\n<br>\n:::')
#           }
#           
#           post <- paste0(post, "\n\n:::\n\n")
#           
#           
#         }
#         post
#         
#         
#         
#       }
#     }
#     
#   }
# )

```

```{r}
#| label: metadatasetup
#| echo: false
#| eval: false
# is_empty = function(x) {
#   is.null(x)  || is.na(x)  || is.nan(x) || length(x) == 0 || x == ""
# }
# 
# 
# 
# 
# 
# 
# # If yaml is just a character, assign to a field called name
# character2name <- function(x) {
#   if (is.character(x)) {
#     list(name = x)
#   } else {
#     x
#   }
# }
# 
# 
# affiliation_namer <- function(d) {
#   # If affiliation is not given.
#   # print(d)
#   if (is.null(d$affiliations)) {
#     d$affiliations <- map(1, \(x) tibble(name = "Unaffiliated"))
#   }
#   if (is.character(d$affiliations)) {
#     d$affiliations <- map(d$affiliations, \(x) tibble(name = x))
#   }
#   if (is.list(d$affiliations)) {
#     d$affiliations <- map(d$affiliations, \(dd) as_tibble(compact(dd)))
#   }
#     
#   d
# }  
# 
#   
#   
# 
# f_author_affiliations <- function(yml) {
#   yml %>%
#     compact() %>% 
#     map(character2name) %>% 
#     map(affiliation_namer) %>% 
#     map(as_tibble) %>%
#     map(\(d) rename(d, any_of(c(roles = "role")))) %>%
#     map(\(d) {
#       if ("roles" %in% colnames(d)) {
#         if (is.list(d |> pull(roles))) {
#           # pull(d, roles) |> unlist() |> print()
#           d <- mutate(d, role_name = map(roles, \(x) {
#             if (is.list(x)) names(x) else x
#           })) |> 
#             unnest(role_name) |> 
#             mutate(role_degree = map(roles, \(x) {
#               if (is.list(x)) x[[1]] else "lead"
#             })) |> 
#             unnest(role_degree) |> 
#             select(-roles) |> 
#             rename(roles = role_name)
#           }
#       }
#       d
#     }) |> 
#     bind_rows() %>% 
#     bind_rows(
#       tibble(
#         id = character(0),
#         number = integer(0),
#         name = character(0),
#         url = character(0),
#         email = character(0),
#         affiliations = list(0),
#         fax = character(0),
#         orcid = character(0),
#         note = character(0),
#         roles = character(0),
#         acknowledgements = character(0),
#         corresponding = logical(0),
#         `equal-contributor` = logical(0),
#         deceased = logical(0)
#       )
#     ) %>% 
#     nest(roles = roles) %>% 
#     mutate(affiliations = map(affiliations, \(d) {
#       colnames(d) <- paste0("affiliations_", colnames(d))
#       d
#     })) %>% 
#     rename(author = name,
#            author_number = number,
#            author_url = url) %>%
#     group_by(author) %>%
#     nest() %>%
#     ungroup() %>%
#     mutate(author_id = row_number(), .before = 1L) %>%
#     unnest(data) %>% 
#     unnest(affiliations) %>% 
#      bind_rows(
#       tibble(  id = character(0),
#                number = character(0),
#                name = character(0),
#                department = character(0),
#                address = character(0),
#                city = character(0),
#                region = character(0),
#                `postal-code` = character(0),
#                country = character(0),
#                url = character(0),
#                ref = character(0)
#       ) %>%
#         rename_with(\(x) paste0("affiliations_",x))
#     ) %>% 
#     unite(
#       regioncode,
#       affiliations_region,
#       `affiliations_postal-code`,
#       remove = F,
#       sep = " ",
#       na.rm = TRUE
#     ) %>%
#     unite(
#       affiliations_default,
#       affiliations_city,
#       affiliations_region,
#       affiliations_country,
#       na.rm = TRUE,
#       remove = F,
#       sep = ", "
#     ) %>%
#     unite(
#       mailing,
#       affiliations_address,
#       affiliations_city,
#       regioncode,
#       affiliations_country,
#       sep = ", ",
#       na.rm = TRUE
#     ) %>%
#     unite(
#       affiliations,
#       affiliations_department,
#       affiliations_name,
#       sep = ", ",
#       na.rm = T,
#       remove = F
#     ) %>%
#     unique() %>% 
#     mutate(rowid = row_number())  %>%
#     group_by(affiliations)  %>%
#     nest() %>%
#     ungroup() %>%
#     mutate(affiliations_row = row_number()) %>%
#     unnest(data) %>%
#     mutate(affiliations_id = ifelse(is.na(affiliations_id),
#                                     ifelse(!is.na(affiliations_ref), 
#                                            affiliations_ref,
#                                            paste0("aff_id_",affiliations_row)),
#                                     affiliations_id)) %>% 
#     mutate(affiliations = ifelse(affiliations == "", NA_character_, affiliations)) %>% 
#     arrange(affiliations_id, is.na(affiliations)) %>% 
#    group_by(affiliations_id) %>% 
#    tidyr::fill(starts_with("affiliations")) %>% 
#    ungroup()  %>% 
#     mutate(affiliations = ifelse(
#       is.null(affiliations) | is.na(affiliations) | affiliations %in% c("NULL", "", "Unaffiliated"),
#       ifelse(
#         is.na(affiliations_default) |
#           affiliations_default %in% c("NULL", "", "Unaffiliated"),
#         "Unaffiliated",
#         affiliations_default
#       ),
#       affiliations
#     )) %>% 
#     select(-affiliations_row) %>% 
#     arrange(rowid) %>% 
#     select(-rowid) %>% 
#     group_by(affiliations) %>% 
#     nest() %>%
#     ungroup() %>% 
#     mutate(affiliations_row = row_number()) %>%
#     unnest(data) %>%
#     group_by(author) %>% 
#     mutate(affs = paste0(affiliations_row, collapse = ",")) %>%
#     ungroup() %>% 
#     mutate(
#       max_author = max(author_id, na.rm = TRUE),
#       max_affiliations = max(affiliations_row, na.rm = TRUE),
#       count_affs = length(unique(affs)),
#       author_display = ifelse(
#         count_affs == 1 | max_author == 1,
#         author,
#         paste0(author, "^", affs, "^")
#       ),
#       affiliations_display = ifelse(
#         count_affs == 1 |
#           max_author == 1,
#         affiliations,
#         paste0("^", affiliations_row, "^", affiliations)
#       )
#     ) 
# 
#   
# }
# 
# 
# 
#   
# f_author_display <- function(d) {
#   d %>%
#   arrange(author_id) %>% 
#   pull(author_display) %>%
#   unique() %>%
#   knitr::combine_words()
# }
# 
# f_affiliations_display <- function(d) {
#   d %>% 
#   pull(affiliations_display) %>% 
#   unique() %>% 
#   paste0(collapse = "\n\n") 
# }
# 
# f_author_affiliations_display <- function(authors, affiliations) {
#   if (all(c(authors, affiliations) == "")) {
#     s <- ""
#   } else {
#     s <- paste("\n\n<br>\n\n:::{.Author}",
#                authors,
#                affiliations,
#                ":::",
#                sep = "\n\n")
#   }
#   s
# }
# 
# f_orcids_display <- function(author_affiliations) {
#   author_affiliations %>%
#     select(author, orcid) %>%
#     unique() %>%
#     filter(!orcid == "NULL") %>%
#     mutate(
#       orcid_display = paste0(
#         author,
#         " ![Orcid ID Logo: A green circle with white letters ID](_extensions/wjschne/apaquarto/ORCID-iD_icon-vector.svg){width=16px} https://orcid.org/",
#         orcid
#       )
#     ) %>%
#     pull(orcid_display) %>%
#     unique() %>%
#     paste0(collapse = "\n\n")
# }
# 
# 
# 
# f_correspondings <- function(author_affiliations) {
#   s <- author_affiliations %>%
#     filter(corresponding) %>%
#     select(author) %>%
#     unique() %>%
#     pull()
#   if (length(s) > 1) stop(paste0("More than one author is set as the corresponding author. Set corresponding to `true` for only one of these authors:\n", knitr::combine_words(s), "."))
# 
# if (length(s) == 0) 
#   return(FALSE)
# }
# 
# f_corresponding_author_display <- function(author_affiliations, corresponding) {
#   author_affiliations %>% 
#   filter(corresponding) %>% 
#   slice(1) %>% 
#   select(author, mailing, affiliations, email) %>% 
#   mutate(email = ifelse(is.na(email), NA, paste0("Email: ", email)),
#          mailing = ifelse(mailing == "", NA, mailing),
#          corresponding_text = "Correspondence concerning this article should be addressed to ") %>% 
#   unite(corresponding_text, corresponding_text, author, sep = " ", na.rm = T, remove = T) %>% 
#    unite(corresponding_text, corresponding_text, affiliations, mailing, email, sep = ", ", na.rm = T, remove = T) %>% 
#   pull(corresponding_text)
# }
# 
# f_author_note_second_paragraph <- function(yml) {
#   if (is.null(yml$`author-note`$`status-changes`)) {
#     s <- ""
#   } else {
#     s <-
#       yml$`author-note`$`status-changes` %>%
#       map(\(x) ifelse(is.null(x), NA, x)) %>%
#       as_tibble() %>%
#       unite(
#         paragraph,
#         everything(),
#         sep = " ",
#         remove = T,
#         na.rm = T
#       ) %>%
#       pull(paragraph)
#   }
#   s
# }
# 
# f_author_roles <- function(yml) {
#   s <- yml %>% 
#     compact() %>% 
#     map(character2name) %>% 
#   map_df(\(x) tibble(author = pluck(x, "name"), roles = list(pluck(x, "roles") ))) %>% 
#   mutate(role_length = map_dbl(roles, length)) %>% 
#   filter(role_length > 0) %>% 
#   mutate(role_list = map_chr(roles, knitr::combine_words),
#          role_author = paste0("*",author, "*: ", role_list)) %>% 
#   pull(role_author) %>% 
#   paste0(collapse = "; ")
#   
#   if (s == "") {
#     s
#   } else {
#     if (length(yml) > 1) {
#       paste0("Author roles were classified using the Contributor Role Taxonomy (CRediT; https://credit.niso.org/) as follows:\n",s)
#     }
#   }
# }
# 
# f_author_note_third_paragraph <- function(yml) {
#   if (is.null(yml$`author-note`$disclosures)) {
#     s <- ""
#   } else {
#     s <- yml$`author-note`$disclosures %>%
#       map(\(x) ifelse(is.null(x), NA, x)) %>%
#       as_tibble() %>%
#       unite(
#         paragraph,
#         everything(),
#         sep = " ",
#         remove = T,
#         na.rm = T
#       ) %>%
#       pull(paragraph)
#   }
#   s
# }
  
## yml_metadata <- get_metadata()
## yml <- yml_metadata$author



# f_author_note_blanks <- function(yml) {
#   if (!is_docx) {
#     blanks <- 1
#   } else if (is.null(yml$`author-note`$`blank-lines-above-author-note`)) {
#     blanks <- 3
#   } else {
#     blanks <- yml$`author-note`$`blank-lines-above-author-note`
#   }
#   blanks  
# }
# 
# f_title_blanks <- function(yml) {
#   if (!is_docx) {
#     blanks <- 1
#   } else if (is.null(yml$`blank-lines-above-title`)) {
#     blanks <- 2
#   } else {
#     blanks <- yml$`blank-lines-above-title`
#   }
#   paste0(rep("<br>", blanks), collapse = "\n\n")
# }
# 
# 
# 
# 
# f_author_note_display <- function(yml) {
#   
#   author_note_second_paragraph <- f_author_note_second_paragraph(yml)
#   author_note_third_paragraph <- f_author_note_third_paragraph(yml)
#   author_note_blanks <- f_author_note_blanks(yml)
#   title_blank_display <- f_title_blanks(yml)
#   author_role_display <- f_author_roles(yml$author)
#   
#   if (all(
#     c(
#       display_orcids,
#       author_note_second_paragraph,
#       author_note_third_paragraph,
#       display_corresponding_author,
#       author_role_display
#     ) == ""
#   )) {
#     s <- ""
#   } else {
#     s <- paste(
#       paste0(rep("<br>", author_note_blanks), collapse = "\n\n"),
#       ":::{.AuthorNote}",
#       "# Author Note",
#       display_orcids,
#       author_note_second_paragraph,
#       author_note_third_paragraph,
#       author_role_display,
#       display_corresponding_author,
#       ":::",
#       sep = "\n\n"
#     )
#   }
#   s
# }
# 
# f_keywords_display <- function(yml) {
#   if (is.null(yml$keywords)) {
#     s <- NULL
#   } else {
#     s <-  paste0("*Keywords*: ", paste0(yml$keywords, collapse = ", "))
#     
#   }
#   s
# }
# 
# f_title_display <- function(title, subtitle) {
#   if (is_empty(title)) return(NULL)
#   strtitle <- trimws(title) %>% str_remove(":$")
#   if (!is_empty(subtitle)) {
#     strtitle <- paste0(strtitle, ": ", subtitle)
#   } 
#   strtitle <- paste0("# ", strtitle, " {.title}")
# }
# 
# f_title_heading_display <- function(title, subtitle) {
#   if (is_empty(title)) return(NULL)
#   strtitle <- trimws(title) %>% str_remove(":$")
#   if (!is_empty(subtitle)) {
#     strtitle <- paste0(strtitle, ": ", subtitle)
#   } 
#   strtitle <- paste0("# ", strtitle)
# }
# 
# f_abstract_display <- function(yml) {
#   if (is.null(yml$abstract)) {
#     s <- ""
#   } else {
#     s <- paste0("# Abstract\n\n", yml$abstract)
#   }
# }
# 
# # yml <- yml_metadata$author
# 
# yml_metadata <- get_metadata()
# d_author_affiliations <- f_author_affiliations(yml_metadata$author)
# 
# display_authors <- f_author_display(d_author_affiliations)
# 
# display_affiliations <- f_affiliations_display(d_author_affiliations) 
#   
# display_author_affiliations <- f_author_affiliations_display(
#   display_authors,
#   display_affiliations
# )
# 
# display_orcids <-  f_orcids_display(d_author_affiliations)
# correspondings <- f_correspondings(d_author_affiliations)
# 
# # Skip corresponding author if none was defined.
# if(identical(correspondings, FALSE)) {
#   display_corresponding_author <- NULL
# } else {
#   display_corresponding_author <- f_corresponding_author_display(
#   d_author_affiliations,
#   correspondings)
# }
# 
# display_author_note <- f_author_note_display(yml_metadata)
# 
# 
# 
# display_keywords <- f_keywords_display(yml_metadata)
# 
# 
# 
# 
# display_title <- f_title_display(yml_metadata$title , yml_metadata$subtitle)
# display_title_heading <- f_title_heading_display(yml_metadata$title , yml_metadata$subtitle)
# display_abstract <- f_abstract_display(yml_metadata)
# 
# 
# # 
# # if (is_docx) {
# #   if (!interactive()) {
# #   library(officer)
# #   if (!is.null(yml_metadata$shorttitle)) {
# #     running_header <- str_to_upper(yml_metadata$shorttitle)
# #   } else if (!is.null(yml_metadata$title)) {
# #     running_header <- str_to_upper(yml_metadata$title)
# #   } else {
# #     running_header <- "SHORT TITLE"
# #   }
# #   
# #   read_docx("_extensions/wjschne/apaquarto/apaquarto.docx") %>%
# #     headers_replace_all_text("Running Header", running_header) %>%
# #     print("apa_processed.docx")
# #   
# # }
# # }
# 

    



```


