Confusion with Dirac notation in quantum mechanics My professor was showing us how to derive the ground state wavefunction for the quantum harmonic oscillator. He begins with the annihilation operator acting on the lowest energy eigenvector:
$$a|E_0\rangle = 0$$
Then he projects the equation onto the position eigenvector: 
$$\langle x|a|E_0\rangle = 0$$
Here are the first couple steps:

\begin{align}
\hat a | E_0 \rangle & =0 \\
\left(\frac{1}{b\sqrt{2}}\hat{x}+\frac{ih}{\hbar \sqrt{2}}\hat{p}\right)|E_0 \rangle & =0 \\
\langle x |\left(\frac{1}{b\sqrt{2}}\hat{x}+\frac{ih}{\hbar \sqrt{2}}\hat{p}\right)|E_0 \rangle & =0\\
\left(\frac{x}{b\sqrt{2}}+\frac{b}{\sqrt{2}}\frac{\mathrm d}{\mathrm d x}\right) \langle x|E_0\rangle &=0\\
\frac{x}{b\sqrt{2}}\psi_0(x)+\frac{b}{\sqrt{2}}\frac{\mathrm d \psi _0}{\mathrm d x}&=0
\end{align}

What I found confusing was the third line. He appears to be "pulling out" an operator which is sandwiched between a bra and a ket vector. I had initially thought that only constants (scalars) can be pulled out when sandwiched between a bra and a ket. I am poorly versed in Dirac notation and am clearly missing something. So my question is:
When are we allowed to "pull out" an operator sandwiched between a bra and a ket? 
 A: It is just how the operators work in the position basis. I will show how it works for the position operator. The momentum operator can be handled similarly
First, we know that matrix elements of the position operator in the position basis are given by $\langle x|\hat X|x'\rangle=x'\delta(x'-x)$. Second, we know the position basis vectors form a complete basis, so $\int\text dx'|x'\rangle\langle x'|=1$. Therefore, for any state vector $|\psi\rangle$ we have
$$\langle x|\hat X|\psi\rangle=\int\text dx'\langle x|\hat X|x'\rangle\langle x'|\psi\rangle=\int\text dx'x'\delta(x'-x)\langle x|\psi\rangle=x\langle x|\psi\rangle$$
So, we aren't "pulling out" the operators. This is just the result for when these operators are expressed in the position basis. "Pulling out" the operator would mean, for example
$$\langle x|\hat X|\psi\rangle=\hat X\langle x|\psi\rangle$$
which is not valid.
A: The way to "pull out" the operator is to write it formally in ket notation, so that it acts naturally on kets. For example (in natural units with $\hbar=1$)
$$\mathbf P = -\int d^3\mathbf x | \mathbf x \rangle i \nabla \langle \mathbf x|.$$
Then you have 
$$\langle \mathbf x|\mathbf P |\psi \rangle = -\int d^3\mathbf y \langle \mathbf x| \mathbf y \rangle i \nabla \langle \mathbf y|\psi \rangle = -i \nabla \langle \mathbf x|\psi \rangle.$$
Similarly 
$$\mathbf X = \int d^3\mathbf x | \mathbf x \rangle \mathbf x \langle \mathbf x|.$$
Then 
$$\langle \mathbf x|\mathbf X |\psi \rangle = \int d^3\mathbf y \langle \mathbf x| \mathbf y \rangle \mathbf y \langle \mathbf y|\psi \rangle = \mathbf x \langle \mathbf x|\psi \rangle.$$
