Given that $f(E)$ is compact if and only if $E$ is, can we deduce the continuity of $f$? Let $(X_1,d_1)$ and $(X_2,d_2)$ be metric spaces. A criterion for the global continuity of some $f:X_1\to X_2$ is that for all closed $E\subseteq X_2$, $f^{-1}(E)$ is closed. This is a corollary of the analogous theorem for counterimages of open subsets of the codomain.
Another necessary condition is that the image of any compact subset of $X_1$ be compact.
But it is not sufficient: e.g. in $\mathbb{R}$, $$
f(x)=
\begin{cases}
x & x\ge 0\\
\sin\frac1x & x <0
\end{cases}
$$ satisfies it, but it is discontinuous in $x_0=0$. I noticed that, on the other hand, $f((-1,1))=[-1,1]$ so I tried strengthening the condition, i.e. requiring the preimage of any compact subset of $X_2$ to be compact.
Vacuously, it works if $X_1$ and $X_2$ are discrete and finite because then all of their subsets are compact and $f $ is continuous in every point of $X_1$ because each one is isolated.
By contrapositive, I think I have proved it also for $X_1\subseteq\mathbb{R}=X_2$, considering a point of discontinuity of the different kinds (except removable discontinuites not included in the domain, since thus the function is still continuous on it). I haven't really tried to generalise, so here's the question:

Let $(X_1,d_1)$ and $(X_2,d_2)$ be metric spaces. Let $f:X_1\to X_2$ be such that for all $E\subseteq X_1$, $f(E)$ is compact if and only if $E$ is. Must $f$ be continuous?


Yes, $f$ must be continuous. For metric spaces, continuity is equivalent to sequential continuity (this requires some choice, but topology without choice is very strange, so we assume choice anyway).
So suppose that $X_1, X_2$ are metric spaces, and $f \colon X_1 \to X_2$ is not continuous at $p$. Then there is a sequence $(x_n)_{n\in\mathbb{N}}$ in $X_1 \setminus \{p\}$ and an $\varepsilon > 0$ such that $x_n \to p$ and $d_2(f(x_n),f(p)) \geqslant \varepsilon$ for all $n$. The set $A := \{ x_n : n \in \mathbb{N}\}$ is not compact, while $A \cup \{p\}$ is compact. But since $f(p)$ has positive distance from $f(A)$, the set $f(A)$ is compact if and only if $f(A) \cup \{f(p)\} = f(A\cup \{p\})$ is compact. So either we have found a compact set whose image isn't compact, or we have found a non-compact set whose image is compact.
