# List of to do's with chapter AND section, and skipping ch/sect without to do's

I have defined a command for the to do's:

\documentclass{book}
\usepackage{graphicx}
\usepackage{hyperref}
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{amsfonts}
\usepackage{mathtools,etoolbox}
\usepackage{float}
\usepackage{amstext} % for \text macro
\usepackage{array}
\usepackage{tocloft}
\usepackage{xcolor}

\newcounter{TotTodos}
\newcommand{\listtodosname}{List of to do's (\arabic{TotTodos})}
\newlistof{todos}{todo}{\listtodosname}
\newcounter{todo}[chapter]
\newcommand\todo[1]{
\refstepcounter{todo}
\phantomsection
\label{todo:\thechapter.\thetodo}\stepcounter{TotTodos}
\textcolor{red}{To do \thetodo} \textcolor{gray}{#1}
{\protect\numberline{\thechapter.\thetodo} #1}
}

% change the cmd chapter to add the chapterts to the list of todo's
\makeatletter
\let\ori@chapter\@chapter
\def\@chapter[#1]#2{\ori@chapter[#1]{#2}%
\fi}
\makeatother

\begin{document}
\chapter{First chapter}
\todo{a}

\section{Section 1.1}
\todo{b}
\section{Section 1.2}
\todo{c}

\section{Section 1.3}

\chapter{Middle chapter}

\chapter{Second chapter}

\section{Section 2.1}
\todo{d}

\section{Section 2.2}

\section{Section 2.3}
\todo{e}

\chapter{Last chapter}

\phantomsection
\listoftodos

\end{document}


This command works fine, generating a list of to do's organized per chapters. I tried to enhance it to list in addition the sections, but changing chapter with section was not enough.

I would like to enhance the code in such a way that

1. chapters and sections are listed in the index of to to's

2. chapters and sections are not printed if there is no to do' under them (the command for the addition of the chapter /section line to the todos toc should be saved somewhere and only executed by the first occurrence of a to do) done

Here is also a picture of the actual PDF:

The result should be

List of to dos (5)

1 First chapter
1.1 a
1.1 Section 1.1
1.2 b
1.2 Section 1.2
1.3 c

2 Second chapter
2.1 Section 2.1
2.1 d
2.3 Section 2.3
2.2 e


EDIT 1 The point (2) is solved and the code in the question has been actualized. Open is only the addition of the section.

• Perhaps unrelated, but you're loading hyperref ways too early – Christian Hupfer Nov 18 '18 at 19:47
• Suggestion: texdoc todonotes. – Fran Nov 18 '18 at 20:20
• @ChristianHupfer were should it be? at the end? what are the consequences? – PeptideChain Nov 18 '18 at 20:35
• @Fran thank you for the hint, but the package (besides the dependencies) does not even structures the to do's in chapter, my main goal – PeptideChain Nov 18 '18 at 20:36
• The tricky bit is NOT listing the chapters and sections without todos. Basically, you need to check the current chapter and section against the last one listed, THEN list (\addcontentsline) the new chapter and/or section. – John Kormylo Nov 18 '18 at 21:44