Integrate $\int\frac{\cos^2(x)-x^2\sin(x)}{(x+\cos(x))^2}dx$

\begin{equation} \int\frac{\cos^2 x-x^2\sin x }{(x+\cos x)^2}dx \end{equation}

Divide both numerator and denominator by $x^2\cos^2 x$

\begin{equation} \int\frac{\cos^2 x-x^2\sin x }{(x+\cos x)^2}dx =\int\frac{\dfrac{1}{x^2}-\dfrac{\sin x}{\cos^2 x}}{(\dfrac{1}{\cos x}+\dfrac{1}{x})^2}dx =\frac{1}{\dfrac{1}{\cos x}+\dfrac{1}{x}} + C =\frac{x\cos x}{x + \cos x} + C \end{equation}


When you see an integral like that, although you quickly find $u=x+\cos x$ won't work, you can't help but think there'll be a nice antiderivative of the form $\frac{f}{x+\cos x}$. So now, we want to solve $$\cos^2x-x^2\sin x=(x+\cos x)f^\prime-(1-\sin x)f.$$Can we write the left-hand side as a linear combination of $x+\cos x,\,1-\sin x$? After a little experimenting, yes: it's $$x\cos x-x^2\sin x+\cos^2x-x\cos x\sin x-x\cos x+x\cos x\sin x\\=(x+\cos x)(\cos x-x\sin x)-x\cos x(1-\sin x),$$implying the choice $f=x\cos x,\,f^\prime=\cos x-x\sin x$, which happily are consistent.


Note that the derivative of $x + \cos(x)$ in the denominator is $1-\sin(x)$ . We can try to make this term appear in the numerator and then integrate by parts. We have $$ \frac{\cos^2(x)-x^2\sin(x)}{(x+\cos(x))^2} = \frac{\cos^2(x) - x^2 + x^2(1-\sin(x))}{(x+\cos(x))^2} = \frac{\cos(x) - x}{x+\cos(x)} + x^2 \frac{1-\sin(x)}{(x+\cos(x))^2} \, ,$$ so \begin{align} \int \frac{\cos^2(x)-x^2\sin(x)}{(x+\cos(x))^2} \, \mathrm{d}x &= \int \frac{\cos(x) - x}{x+\cos(x)} \, \mathrm{d} x - \frac{x^2}{x+\cos(x)} + \int \, \frac{2 x}{x+\cos(x)}\mathrm{d} x \\ &= x - \frac{x^2}{x+\cos(x)} = \frac{x \cos(x)}{x+\cos(x)} \end{align} as desired.